iphone - 编写父 View Controller 的终极指南

标签 iphone ios ipad uiviewcontroller

精简版

如果我正在编写自己的自定义 Split View Controller ,我需要做什么才能使 subview Controller 按预期工作?

例如:发送viewWillAppear:等。

长版

背景

不久前我回答了以下问题:
Switch between UIViewControllers using UISegmentedControl

回答如下:

The right way to do it is to have the controller handling the UISegmentedControl add the views of the controllers as subviews.

[self.view addSubview:controller.view];

It's your responsibility to send viewWillAppear: and so on.

但是,tc。指出这并不像听起来那么微不足道:

No. View controllers are not meant to be used like that - controller will miss out on a lot of the UIViewController magic that's taken for granted (namely -view{Will,Did}{Appear,Disappear}: and -shouldRotateToViewOritentation:).

By "magic", I'm referring to everything UIKit does behind the scenes. You also forgot -parentViewController (which is important for things like modal view controllers). Additionally, somewhere in the depths of UIKit, it automatically calls -viewSomethingSomething: for you, so you might get -viewDidDisappear: twice! (I can't remember the exact details, but there's another user reporting that all you need to do is call -viewWillAppear: and the other three methods happen automatically.) The key issue is that Apple doesn't document the "magic" or how it changes between OS updates.

从那时起,我一直在考虑应该编写一份指南,说明父 View Controller 中需要存在的内容,以便 subview Controller 按预期工作。 Apple 的文档没有涵盖这一点,Google 也没有太大帮助,所以现在我希望在 stackoverflow 社区中找到这方面的知识。

我已经写了几个这样的 Controller ,它们似乎都可以工作,但我忍不住想知道我是否错过了重要的 View Controller 魔法。

最佳答案

我认为最好的解决办法是“不要那样做”。与其希望您可以复制 UIViewController 的所有行为而不因使用私有(private) API 调用而被拒绝,为什么不创建非 UIViewController Controller 对象来管理您的 subview 呢? “ Controller ”不一定是 UIViewController

至少您需要为 parentViewControllersplitViewControllernavigationControllertabBarController 覆盖或混合替换 getter code> 和 interfaceOrientation(可能还有 modalViewController)。对于每个属性,您需要确保 UIKit 调用的任何私有(private) setter 仍按预期工作,并且通过直接修改 UIViewController ivars 对这些值所做的任何更改也正确反射(reflect)在您的实现中。

您还需要弄清楚 UIKit 如何确定哪个 UIViewController 当前处于事件状态并且应该接收 View Controller 生命周期方法,因为您需要确保将这些方法发送到您的容器 View Controller ,而不仅仅是其中之一 children 。

您还必须希望您没有构建一个不受任何 Apple View Controller 类支持的情况。例如,如果它们有一个 parentViewController 但它们的 navigationControllertabBarControllersplitViewController 都是没有?

最后,您需要了解每个 iOS 版本对这些私有(private)实现细节的任何更改。

关于iphone - 编写父 View Controller 的终极指南,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6019890/

相关文章:

iPhone内存释放问题

iphone - UIImageView坐标到 subview 坐标

iOS 应用程序错误 - 无法将自身添加为 subview

ios - 在 Core Data 中,NSManagedObjects 上 Date 属性的有效默认值是什么

objective-c - 我们如何创建带注释的 PDF

javascript - 将 objective-c 变量传递给 ios 中的 javascript

jquery - Phonegap AJAX 调用失败

ios - MKPolyline -> NSKeyedArchiver -> NSData SIGABRT

iphone - 如何以编程方式获取iphone的IP地址

iphone - 如果你让你的iPhone应用程序变得通用,你能在未来的版本中撤消它吗?