我正在尝试使用以下代码将 subview Controller 添加到包含在 UINavigationController
中的 UIViewController
中:
- (void)buttonTapped:(id)sender
{
MyChildController *viewController = [self.storyboard instantiateViewControllerWithIdentifier:@"MyChild"];
[self addChildViewController:viewController];
[self.view addSubview:viewController.view];
[viewController didMoveToParentViewController:self];
viewController.view.alpha = 0.0f;
[UIView animateWithDuration:0.4 animations:^{
viewController.view.alpha = 1.0f;
}];
}
但这是结果:
如您所见,UINavigatioBar
和 UIToolbar
仍在 subview Controller 之上。我怎样才能把 subview Controller 放在最上面?我已经尝试用以下代码替换代码:
[self.navigationController addChildViewController:viewController];
[self.navigationController.view addSubview:viewController.view];
[viewController didMoveToParentViewController:self.navigationController];
但是这样 viewController
的 viewDidAppear:animated
不会被调用。我不知道,为什么。
最佳答案
@Sam的评论是正确的。您需要调用 beginApperanceTransition:animated:
和 endAppearanceTransition
来触发 viewDidAppear
。 UINavigationController
之所以在添加 subview Controller 时不调用viewDidAppear
,是因为它重写了其容器组合方法,以防止程序员以奇怪的方式添加 subview Controller 地方。在您的情况下,它不希望您的 subview 覆盖导航栏。导航 Controller 的正确用法是让子项出现在导航栏下方。尽管如此,您仍然可以通过手动告诉 child 何时出现以及何时结束出现来强制使用此非标准 UI。
给 UINavigationController 添加一个 child
MyChildViewController* child = [[MyChildViewController alloc] init];
[self.navigationController addChildViewController:child];
child.view.frame = self.navigationController.view.bounds;
[self.navigationController.view addSubview:child.view];
child.view.alpha = 0.0;
[child beginAppearanceTransition:YES animated:YES];
[UIView
animateWithDuration:0.3
delay:0.0
options:UIViewAnimationOptionCurveEaseOut
animations:^(void){
child.view.alpha = 1.0;
}
completion:^(BOOL finished) {
[child endAppearanceTransition];
[child didMoveToParentViewController:self.navigationController];
}
];
从 UINavigationController 中移除一个 child
[child willMoveToParentViewController:nil];
[child beginAppearanceTransition:NO animated:YES];
[UIView
animateWithDuration:0.3
delay:0.0
options:UIViewAnimationOptionCurveEaseOut
animations:^(void){
child.view.alpha = 0.0;
}
completion:^(BOOL finished) {
[child endAppearanceTransition];
[child.view removeFromSuperview];
[child removeFromParentViewController];
}
];
关于iphone - 将 subview Controller 添加到 UINavigationController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19257999/