ios - UIViewController setView nil 自动从 superview 中移除

标签 ios cocoa-touch uiviewcontroller uikit

在 UIViewController 上调用 setView 会自动从其父 View 中删除当前 View 。我找不到这个记录。在我的情况下,我想动态地将 UIViewController 对象交换为另一个对象,同时保持我的 View 结构。我正计划将 View 重新链接到新 Controller ,但可惜,这不起作用。

一般来说,自动从其父 View 中删除 View 似乎是一个明智的决定。文档应该反射(reflect)这一点。

(对于任何认为以这种方式交换 View Controller 对象是一个非常糟糕的主意的人,让我补充一下,我正在交换的 Controller 是现有 Controller 的子类。这种方法非常适合向 View 添加功能是另一个的延伸。)

最佳答案

这就是我解决它的方法:

UIView *viewToKeep = self.viewController.view;
UIView *superview = viewToKeep.superview;
self.viewController.view = nil;  // removes the view from its superview

UIViewController *swapInViewController = [[UIViewController alloc] init];
swapInViewController.view = viewToKeep;
[superview addSubview: viewToKeep];
[viewToKeep applyConstraintsToFillSuperview];  // a helper to add auto layout constraints that make the view always fill it's parent
self.viewController = swapInViewController;

关于ios - UIViewController setView nil 自动从 superview 中移除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30429113/

相关文章:

iphone - 了解何时对对象调用保留?

swift - 如何从不同的 View Controller 访问引用 socket ?

ios - 在进行最小滚动或点击之前,单元格不会显示在表格 View 中(注意 : nothing happens on a background thread)

ios - 在 UICollectionView 中创建 2 x 2 水平网格?

ios - 检测 iOS 3D Touch peek 何时完成(没有弹出)

ios - 在后台线程中将数据保存到 Realm 时发生崩溃。 | iOS | swift 4.2

iphone - 如何获取 NSString 类的方法名称?

ios - 确定事件发送者的最佳方法

ios - 发送数据时出错

ios - 子类中 self 和 super 之间的混淆