设为首页 加入收藏

TOP

presentedViewController 和 presentingViewController 以及 dismissViewControllerAnimated 的使用
2019-08-26 07:06:32 】 浏览:25
Tags:presentedViewController presentingViewController 以及 dismissViewControllerAnimated 使用

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

1:present 控制器的使用

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

1
2
3
[ 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循环的终止条件可以通过控制器的类来判断。

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇NavigationController 下一篇block本质探寻五之atuto类型局部..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目