presentedViewController 和 presentingViewController 以及 dismissViewControllerAnimated 的使用

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

1:present 控制器的使用

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

[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 方法。io

舉例來講,從A控制器跳轉到B控制器,在B控制器中點擊了返回按鈕,指望可以回到A控制器,則B控制器中點擊返回按鈕觸發事件的代碼是:class

[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循環的終止條件能夠經過控制器的類來判斷。im

相關文章
相關標籤/搜索