美文网首页ios开发
presentedViewController 和 presen

presentedViewController 和 presen

作者: 零度_不结冰 | 来源:发表于2018-01-18 10:51 被阅读20次

    presentedViewController 和 presentingViewController 以及 dismissViewControllerAnimated 的使用

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

    1:present 控制器的使用

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

    [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控制器调用

    1

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

    相关文章

      网友评论

        本文标题:presentedViewController 和 presen

        本文链接:https://www.haomeiwen.com/subject/mabioxtx.html