Skip to main content
 首页 » 编程设计

cocoa-touch之像 UIViews 一样在其他 UIViewControllers 中使用 "nest"UIViewControllers 是否明智

2024年10月25日24artech

我有一个相当复杂的 View ,无论如何,对我来说,它有一些带有自定义界面项目的“托盘”。它们滑进和滑出我的根 View 。我想在 View 中嵌套(addSubview)项目。每个都需要在显示之前进行一些设置……并且不能在 IB 中进行配置(它们是 UIView 的子类)。

我想知道为每个“托盘”子类化 UIViewController 是否有意义,然后让 VC 的 View 属性指向“托盘” View ,我可以用我的自定义 UIView 对象填充它。这样我就可以利用 UIViewController 中的 viewDidLoad 等方法。

我不知道其他人这样做 - 至少在我看过的几个样本中。这会造成一种情况,即屏幕上同时显示多个 View Controller 。从导航 Controller 本身一直到 rootViewController 及其 View ,然后是任意数量(好吧,屏幕大小允许)的这些小托盘 View Controller 。如果是这样,响应者链是如何工作的?我假设它会从最低的 UIView 到它的封闭 VC,然后到那个 VC 的父 View ,然后是那个 View 的 VC 等等等等。重复,重复......直到 UIApplication......我是在自找麻烦吗?

或者,我是否只是坚持使用 UIViews 并将 subview 添加到 subview 中等等。等等。

请您参考如下方法:

在 iOS 5.0 之前,特别不推荐这样做,因为不会调用嵌套 View Controller 的生命周期事件(viewWillAppear 等)。见 Abusing UIViewControllers .

With multiple UIViewController’s views visible at once some of those controllers may not receive important messages like -viewWillAppear: or -didReceiveMemoryWarning. Additionally some of their properties like parentViewController and interfaceOrientation may not be set or updated as expected.



新增 iOS 5.0 containment UIViewControllers通过添加 subview Controller 正确处理这些生命周期事件。
- (void)addChildViewController:(UIViewController *)childController 

我花了无数个小时试图让嵌套的 View Controller 在 iOS 4 中工作。我最终做到了,但它需要大量容易出错的胶水代码。然后我在文档中看到了警告。