有时我想将 UIViewController 用作真正的“控制器”而不是带有控制器的视图。也就是说,UIViewController 将获得对现有 UIView 的控制。
在嵌套的 UIViewcontroller 中,我的 UIViewController 的视图是其他视图的子视图。
在某些情况下,UIViewController 可能会控制同一个视图,但不会同时控制。
因此,在委托分配期间,我将确保以前的 UIViewController 停止将视图注册为视图。
UITableView * tvDelegated = (UITableView *)self.delegateForTableController.tvDelegated; //Make sure tvDelegated is not deallocated
UIViewController * vcPreviousViewController = [tvDelegated vcImmediateUIViewController];
assert(vcPreviousViewController.view==tvDelegated);
PO(vcPreviousViewController.view);
PO(vcPreviousViewController.view.superview);
PO(tvDelegated);
PO(tvDelegated.superview);
vcPreviousViewController.view=nil;//if the table view used to have a different tableViewController then disassociate that
PO(vcPreviousViewController.view);
PO(vcPreviousViewController.view.superview);
PO(tvDelegated);
PO(tvDelegated.superview);
基本上,我将指向前一个 ViewController 视图的强指针存储在一个名为 tvDelegated 的变量中。这确保视图不会消失。
结果,首先一切正常:
self.BGtableController.view: <UITableView: 0x1dc0d600; frame = (0 0; 320 548); clipsToBounds = YES; autoresize = W+H; gestureRecognizers = <NSArray: 0x1e485850>; layer = <CALayer: 0x1e4e35b0>; contentOffset: {3, 10}>
self.BGtableController.view.superview: <UIView: 0x1e4bd910; frame = (0 0; 320 548); autoresize = W+H; layer = <CALayer: 0x1e4bd970>>
vcPreviousViewController.view: <UITableView: 0x1dc0d600; frame = (0 0; 320 548); clipsToBounds = YES; autoresize = W+H; gestureRecognizers = <NSArray: 0x1e485850>; layer = <CALayer: 0x1e4e35b0>; contentOffset: {3, 10}>
vcPreviousViewController.view.superview: <UIView: 0x1e4bd910; frame = (0 0; 320 548); autoresize = W+H; layer = <CALayer: 0x1e4bd970>>
执行后vcPreviousViewController.view=nil
, tvDelegated 没有按预期消失,但超级视图消失了。
vcPreviousViewController.view: <UITableView: 0x1dc0b000; frame = (0 0; 320 568); clipsToBounds = YES; autoresize = W+H; gestureRecognizers = <NSArray: 0x1e4cd330>; layer = <CALayer: 0x1e4cddd0>; contentOffset: {3, 10}>
vcPreviousViewController.view.superview: (null)
tvDelegated: <UITableView: 0x1dc0d600; frame = (0 0; 320 548); clipsToBounds = YES; autoresize = W+H; gestureRecognizers = <NSArray: 0x1e485850>; layer = <CALayer: 0x1e4e35b0>; contentOffset: {3, 10}>
tvDelegated.superview: (null)
这是另一件令人惊奇的事情。vcPreviousViewController.view 不会变为 nil。即使我清楚地将 vcPreviousViewController.view 设置为 nil,但变为 nil 的是 vcPreviousViewController.view.superview。