我做了一个简单的测试,以了解有关包含视图控制器的更多信息 我有一个视图控制器,我使用两个按钮的动作添加/删除了一个视图控制器:
- (IBAction)myInfoAddAction:(id)sender {
profileViewController = [[ProfileViewController alloc] init];
[self addChildViewController: profileViewController];
UIView *__view = profileViewController.view;
[self.view addSubview: __view];
[profileViewController didMoveToParentViewController: self];
}
- (IBAction)myInfoRemoveAction:(id)sender {
[profileViewController willMoveToParentViewController: nil];
[profileViewController.view removeFromSuperview];
[profileViewController removeFromParentViewController];
}
班级ProfileViewController
扩展UIViewController
并覆盖willMoveToParentViewController
和didMoveToParentViewController
方法
-( void)willMoveToParentViewController:(UIViewController *)parent
{
[super willMoveToParentViewController: parent];
NSLog(@"willMoveToParentViewController -> %@", self);
}
-( void) didMoveToParentViewController:(UIViewController *)parent
{
[super didMoveToParentViewController: parent];
NSLog(@"didMoveToParentViewController -> %@", self);
}
-( void)viewWillAppear:(BOOL)animated
{
NSLog(@"viewWillAppear -> %@", self);
}
-( void)viewDidDisappear:(BOOL)animated
{
NSLog(@"viewDidDisappear -> %@", self);
}
当我添加视图控制器时,我得到了以下日志:
willMoveToParentViewController -> <ProfileViewController: 0x8c52ea0>
viewWillAppear -> <ProfileViewController: 0x8c52ea0>
didMoveToParentViewController -> <ProfileViewController: 0x8c52ea0>
didMoveToParentViewController -> <ProfileViewController: 0x8c52ea0>
当我删除视图控制器时:
willMoveToParentViewController -> <ProfileViewController: 0x8c52ea0>
didMoveToParentViewController -> <ProfileViewController: 0x8c52ea0>
viewDidDisappear -> <ProfileViewController: 0x8c52ea0>
didMoveToParentViewController -> <ProfileViewController: 0x8c52ea0>
我想知道为什么didMoveToParentViewController
被调用了两次?
谢谢!
答案 0 :(得分:9)
我也有同样的问题。此外,我发现当我在viewDidLoad中添加子视图控制器时,我只有一条消息。我通过删除对[super didMoveToParentViewController:]
的调用来修复它。我认为这个问题与在按钮回调中添加子视图控制器有关,但我不确定为什么这会导致问题。
答案 1 :(得分:0)
可以通过检查当前父视图控制器来过滤掉didMoveToParentViewController
的重复系统调用。在这种情况下,我们可以使用超级调用。
- (void)didMoveToParentViewController:(UIViewController *)parent {
[super didMoveToParentViewController:parent];
if (parent == nil && self.parentViewController == nil) return;
if (parent != nil && self.parentViewController == parent) return;
// From here any code called once
}
答案 2 :(得分:-1)
您必须调用“ viewWillAppear”和“ viewDidDisappear”的超级功能