自学内容网 自学内容网

「iOS」push与present

前言

在此前就学习过视图的push与present。与之对应的退出方法为pop与dismiss。这里进行一次总结。


push与pop

pushViewController 是通过导航控制器入栈的方式切换页面
方法使用为先创建一个视图,后push进栈:

    secondViewController *secondVC = [[secondViewController alloc] init];
   
    [self.navigationController pushViewController:secondVC animated:YES];

pop则是与之对应的弹出视图的方法,具体使用如下:

//返回上一级
[self.navigationController popViewControllerAnimated:YES];

//返回根视图
[self.navigationController popToRootViewControllerAnimated:YES];

//返回指定级数 (objectAtIndex:参数为想要返回的级数)
[self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:0]  animated:YES];

present与dismiss

presentViewController 是通过模态切换的方式切换页面
具体使用方法如下:

    secont_presentViewController *second_Pre = [[secont_presentViewController alloc] init];
    
    [self presentViewController:second_Pre  animated:YES completion:nil];

与push不同,present不需要使用导航控制器。因此不将视图压入导航控制器也可以推出。

对应的弹出视图的方法为dismiss

    [self dismissViewControllerAnimated:YES completion:nil];

使用dismiss弹出多级

PresentedViewController 与 PresentingViewController区别

PresentedViewController和PresentingViewController是UIViewController中的两个属性。

  • presentedViewController:The view controller that was presented by
    this view controller or its nearest ancestor. 由这个视图控制器或它最近的祖先呈现的视图控制器
  • presentingViewController:The view controller that presented this view
    controller (or its farthest ancestor.) 呈现此视图控制器(或其最远祖先)的视图控制器。

当我们对视图A使用present推出视图B时。
A.presentedViewController 就是B控制器;
B.presentingViewController 就是A控制器;

由此,我们可以通过判断presentingViewController属性是否存在,来跳转到根视图

-(void)btn_dismissToRoot
{
    UIViewController *rootVC = self.presentingViewController;
     while  (rootVC.presentingViewController ) {
              rootVC = rootVC.presentingViewController ;
             }
    [rootVC dismissViewControllerAnimated:YES completion:nil];
}

也可以直接dismiss到对应的presentingViewController属性的层级,来跳转到我们需要的视图中
如,跳转到上上个视图

    [self.presentingViewController.presentingViewController dismissViewControllerAnimated:YES completion:nil];

或者通过判断是否为对应子类

-(void)btn_dismissTosecondTwo
{
    UIViewController *rootVC =  self.presentingViewController;
    while (![rootVC isKindOfClass:[secont_presentViewController class]])  {
        rootVC = rootVC.presentingViewController;
    }
    [rootVC dismissViewControllerAnimated:YES completion:nil];
}

实现效果:
请添加图片描述

总结

使用业务逻辑不同,界面推出的方式也不同。
present用于不同业务界面的切换。push用于同一业务不同界面之间的切换。
还值得我们注意的是,当我们present进入一个界面后,是不能push推出下一个界面的。这点会造成界面推出后无法收回,或者无法推出下一个界面的bug,以后遇到了再详细研究吧。


原文地址:https://blog.csdn.net/2301_80253909/article/details/142319506

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!