有時我想用UIViewController作爲真正的「控制器」而不是帶有控制器的視圖。也就是說,UIViewController將獲得對現有UIView的控制權。如何在地球上設置一個UIViewController視圖爲零,使視圖失去了其超視圖?
在嵌套的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不會成爲零。即使我清楚地將vcPreviousViewController.view設置爲nil,vcPreviousViewController.view.superview變成了nil。
Jesly Varghese評論:更好地使用代表或塊(通知機制,如果過度使用,是很多頭疼) – kaspartus
嗯。過度使用任何機制實際上是一種糟糕的做法。如果您的控制器必須與多於一個其他控制器通信,則委託機制不是最佳選擇。 – kaspartus