ios - didMoveToParentViewController 和 willMoveToParentViewController

标签 ios objective-c iphone uiviewcontroller

关于 UIViewController 的 Apple 文档说:

如果您正在实现自己的容器 View Controller ,它必须在调用 removeFromParentViewController 方法之前调用 subview Controller 的 willMoveToParentViewController: 方法,并传入一个父值为零。

当您的自定义容器调用 addChildViewController: 方法时,它会自动调用 willMoveToParentViewController: 在添加之前要添加为 subview Controller 的方法。

如果您正在实现自己的容器 View Controller ,它必须在转换到新 Controller 完成后调用 subview Controller 的 didMoveToParentViewController: 方法,或者如果没有转换,则立即在调用 addChildViewController: 方法之后。

removeFromParentViewController 方法在移除 subview Controller 后自动调用 subview Controller 的 didMoveToParentViewController: 方法。

为什么要调用这些方法?这些方法有什么作用?

ProfileViewController *profile = [[ProfileViewController alloc] init];
profile.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
[self addChildViewController:profile];
[self.view addSubview:profile.view];
[profile didMoveToParentViewController:self];

即使我删除了最后一行,我的代码也能完美运行。有人可以帮我解决这个问题吗?

提前致谢

最佳答案

使用这些方法是因为它是添加或删除 subview Controller 时要遵循的规则。在添加 subview Controller 之前,应首先调用 willMoveToParentViewController 方法,然后调用 didMoveToParentViewController 方法。从父 View Controller 中删除 subview Controller 时,将以相反的顺序调用这些方法。

addChildViewController: 自动调用 [child willMoveToParentViewController:self]。所以应该在 addChildViewController: 之后调用 didMoveToParentViewController。同样,removeFromParentViewController: 自动调用 [child didMoveToParentViewController:nil]。所以应该在 removeFromParentViewController:

之前调用 willMoveToParentViewController:

关于ios - didMoveToParentViewController 和 willMoveToParentViewController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32114179/

相关文章:

ios - 如何为 iOS 构建 Unity3d 插件

objective-c - 如何在 objective-c 中修复“无效的AllXsd值”?

iphone - 如果在 ios 中收到通知时从后台删除应用程序,则不会触发 didReceiveLocalNotification

iphone - iOS私有(private)api使用: _Unwind_Resume

ios - Firebase 云消息在模拟器中有效,但在 IOS 设备上无效

ios - Storyboard导航 - 从堆栈中推送和删除

iphone - 重复淡入/淡出效果以在三个 View 之间切换

iphone - 分层 iPhone 设置文件问题 -- 无法添加到 Settings.bundle

iphone - 如何摆脱控制台中每个 NSLog 语句之前出现的日期和时间

iphone - 有没有办法使用 WebKit 以编程方式下载网页以供离线查看?