presentedViewController 和 presentingViewController 以及 dismissViewControllerAnimated 的使用


在日常的開發中,多控制器之間的跳轉除了使用push的方式,還可以使用 present的方式,present控制器時,就避免不了使用 presentedViewController、presentingViewController ,這兩個概念容易混淆,簡單介紹一下。

1:present 控制器的使用

  使用present的方式,從一個控制器跳轉到另一個控制器的方法如下:

1
2
3
[ self  presentViewController:vc animated: YES  completion:^{
         
}];

2:presentedViewController 與  presentingViewController

  假設從A控制器通過present的方式跳轉到了B控制器,那么 A.presentedViewController 就是B控制器;B.presentingViewController 就是A控制器。

3:dismissViewControllerAnimated 方法的使用

  假設從A控制器通過present的方式跳轉到了B控制器,現在想要回到A控制器,那么需要A控制器調

- (void)dismissViewControllerAnimated: (BOOL)flag completion: (void (^ __nullable)(void))completion

  方法。注意:是想要從B控制器回到A控制器時,需要A控制器調用上面的方法,而不是B控制器。簡單來說,如果控制器通過present的方式跳轉,想要回到哪個控制器,則需要哪個控制器調用 dismissViewControllerAnimated 方法。

舉例來說,從A控制器跳轉到B控制器,在B控制器中點擊了返回按鈕,期望能夠回到A控制器,則B控制器中點擊返回按鈕觸發事件的代碼是:

[self.presentingViewController dismissViewControllerAnimated:YES completion:^{
         
}];

注意:這段代碼是在B中執行,因此 self.presentingViewController 實際上就是A控制器,這樣就返回到了A控制器。

如果多個控制器都通過 present 的方式跳轉呢?比如從A跳轉到B,從B跳轉到C,從C跳轉到D,如何由D直接返回到A呢?可以通過 presentingViewController 一直找到A控制器,然后調用A控制器的 dismissViewControllerAnimated 方法。方法如下:

UIViewController *controller = self;
while(controller.presentingViewController != nil){
    controller = controller.presentingViewController;
}
[controller dismissViewControllerAnimated:YES completion:nil];

PS:如果不是想直接返回到A控制器,比如想回到B控制器,while循環的終止條件可以通過控制器的類來判斷。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM