我做了一个简单的测试,以了解有关包含 View Controller 的更多信息。
我有一个 View Controller ,使用两个按钮的 Action 在其中添加/删除了 View Controller :
- (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);
}
当添加 View Controller 时,得到以下日志:
willMoveToParentViewController -> <ProfileViewController: 0x8c52ea0>
viewWillAppear -> <ProfileViewController: 0x8c52ea0>
didMoveToParentViewController -> <ProfileViewController: 0x8c52ea0>
didMoveToParentViewController -> <ProfileViewController: 0x8c52ea0>
当我删除 View Controller 时:
willMoveToParentViewController -> <ProfileViewController: 0x8c52ea0>
didMoveToParentViewController -> <ProfileViewController: 0x8c52ea0>
viewDidDisappear -> <ProfileViewController: 0x8c52ea0>
didMoveToParentViewController -> <ProfileViewController: 0x8c52ea0>
我想知道为什么
didMoveToParentViewController
被调用两次?谢谢!
最佳答案
我也遇到过同样的问题。此外,我发现在viewDidLoad期间添加 subview Controller 时,只有一条消息。我通过删除对[super didMoveToParentViewController:]
的调用来解决此问题。我认为问题与在通过按钮进行回调时添加 subview Controller 有关,但是我不确定为什么这会引起问题。
关于ios - didMoveToParentViewController调用了两次,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18313888/