presentingViewController、presentedViewController區別


解釋兩個屬性:
presentingViewControllerpresentedViewController

A----(present)-----B----(present)-----C

1、那么 A 就是 B 的 presentingViewController.
2、C 就是 B 的 presentedViewController.

以B為參照:A為presentingViewController, C為presentedViewController

  

 

如題,蘋果自帶的是沒有直接dismissToRootViewController之類的方法,如果需要直接dismiss到最底層的那個控制器,可以自己寫一個dismissToRootViewController方法,
代碼如下:

 

說明:self調用dismiss方法會的時候會判斷self.presentedViewController是否存在,如果存在,就只會將self.presentedViewController給dismiss掉,自己不會dismiss掉。所以我們一直遍歷到最底層的控制器,然后調用dismiss方法,就會將所有的presentedViewController給dismiss掉。

 

presentedViewController 和 presentingViewController 以及 dismissViewControllerAnimated 的使用

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

presentingViewController: 當前控制器是哪個控制器彈出的。由誰彈出。
presentedViewController: 當前控制器彈出的控制器。彈出了誰。

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

[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