您的位置:首页 > 移动开发 > IOS开发

iOS presentedViewController的基本使用

2018-06-26 18:42 706 查看
在日常的开发中,多控制器之间的跳转除了使用push的方式,还可以使用 present的方式,present控制器时,就避免不了使用 presentedViewController、presentingViewController ,这两个概念容易混淆,简单介绍一下。

1. present 控制器的使用

使用present的方式,从一个控制器跳转到另一个控制器的方法如下:

[self presentViewController:vc animated:YES completion:^{

}];


将当前vc设置成rootViewController的方法

MCZhuCeViewController *zhuceVC = [[MCZhuCeViewController alloc] init];
[self presentViewController:[[UINavigationController alloc] initWithRootViewController:zhuceVC] animated:YES completion:nil];


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];

如果不是想直接返回到A控制器,比如想回到B控制器,while循环的终止条件可以通过控制器的类来判断
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  iOS