presentedViewController 和 presentingViewController 以及 dismissViewControllerAnimated 的使用
在日常的開發(fā)中,多控制器之間的跳轉(zhuǎn)除了使用push的方式,還可以使用 present的方式,present控制器時(shí),就避免不了使用 presentedViewController、presentingViewController ,這兩個(gè)概念容易混淆,簡單介紹一下。
1:present 控制器的使用
使用present的方式,從一個(gè)控制器跳轉(zhuǎn)到另一個(gè)控制器的方法如下:
[self presentViewController:vc animated:YES completion:^{
}];
2:presentedViewController 與 presentingViewController
假設(shè)從A控制器通過present的方式跳轉(zhuǎn)到了B控制器,那么 A.presentedViewController 就是B控制器;B.presentingViewController 就是A控制器。
3:dismissViewControllerAnimated 方法的使用
假設(shè)從A控制器通過present的方式跳轉(zhuǎn)到了B控制器,現(xiàn)在想要回到A控制器,那么需要A控制器調(diào)用
1
- (void)dismissViewControllerAnimated: (BOOL)flag completion: (void (^ __nullable)(void))completion
方法。注意:是想要從B控制器回到A控制器時(shí),需要A控制器調(diào)用上面的方法,而不是B控制器。簡單來說,如果控制器通過present的方式跳轉(zhuǎn),想要回到哪個(gè)控制器,則需要哪個(gè)控制器調(diào)用 dismissViewControllerAnimated 方法。
舉例來說,從A控制器跳轉(zhuǎn)到B控制器,在B控制器中點(diǎn)擊了返回按鈕,期望能夠回到A控制器,則B控制器中點(diǎn)擊返回按鈕觸發(fā)事件的代碼是:
[self.presentingViewController dismissViewControllerAnimated:YES completion:^{
}];
注意:這段代碼是在B中執(zhí)行,因此 self.presentingViewController 實(shí)際上就是A控制器,這樣就返回到了A控制器。
如果多個(gè)控制器都通過 present 的方式跳轉(zhuǎn)呢?比如從A跳轉(zhuǎn)到B,從B跳轉(zhuǎn)到C,從C跳轉(zhuǎn)到D,如何由D直接返回到A呢?可以通過 presentingViewController 一直找到A控制器,然后調(diào)用A控制器的 dismissViewControllerAnimated 方法。方法如下:
UIViewController *controller = self;
while(controller.presentingViewController != nil){
controller = controller.presentingViewController;
}
[controller dismissViewControllerAnimated:YES completion:nil];
PS:如果不是想直接返回到A控制器,比如想回到B控制器,while循環(huán)的終止條件可以通過控制器的類來判斷。