在平常的开发中,多控制器之间的跳转除了使用push的方式,还能够使用 present的方式,present控制器时,就避免不了使用 presentedViewController、presentingViewController ,这两个概念容易混淆,简单介绍一下。spa
使用present的方式,从一个控制器跳转到另外一个控制器的方法以下:blog
[self presentViewController:vc animated:YES completion:^{ }];
假设从A控制器经过present的方式跳转到了B控制器,那么 A.presentedViewController 就是B控制器;B.presentingViewController 就是A控制器。事件
假设从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