ios中界面的跳转presentedViewController 、pushViewController及实现返回关闭当前页面

基本介绍

1、有NavigationController导航栏的话,使用[self.navigationColler pushViewController:animated:];和[self.navigationController popViewControllerAnimated:];来进行视图切换。pushViewController是进入到下一个视图,popViewController是返回到上一视图。

2、没有NavigationController导航栏的话,使用[self presentViewController:animated:completion:];和[self dismissViewControllerAnimated:completion:];具体是使用可以从文档中详细了解。

3、 presentedViewController 与  presentingViewController

  假设从A控制器通过present的方式跳转到了B控制器,那么 A.presentedViewController 就是B控制器;B.presentingViewController 就是A控制器。

实现返回关闭当前页面

1、  如果多个控制器都通过 present 的方式跳转呢?比如从A跳转到B,从B跳转到C,从C跳转到D,如何由D直接返回到A呢?可以通过 presentingViewController 一直找到A控制器,然后调用A控制器的 dismissViewControllerAnimated 方法。方法如下:

1

2

3

4

5

UIViewController *controller = self;

while(controller.presentingViewController != nil){

    controller = controller.presentingViewController;

}

[controller dismissViewControllerAnimated:YES completion:nil];

PS:如果不是想直接返回到A控制器,比如想回到B控制器,while循环的终止条件可以通过控制器的类来判断。

2、使用presentViewControllerAnimated方法从A->B->C,若想在C中直接返回A,则可这样实现:

C中返回事件:

  • void back  
  • {  
  •       [self dismissViewControllerAnimated:NO];//注意一定是NO!!  
  •       [[NSNotificationCenter  defaultCenter]postNotificationName:@"backback" object:nil];  
  • }

    然后在B中,

    1. //在viewdidload中:  
    2. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(back) name:@"backback" object:nil];  
    3.   
    4. -(void)back  
    5. {  
    6.      [self dismissViewControllerAnimated:YES];  
    7. }

3、使用pushViewController方法从A->B->C,若想在C中直接返回A,则可这样实现:

C中返回事件:

#pragma mark - 继承父类的返回点击事件

-(void)onClickGobackBtn:(UIButton *)button{

    //返回到根视图控制器

    [self.navigationController popToRootViewControllerAnimated:NO];//注意一定是NO!

  

    [[NSNotificationCenter  defaultCenter] postNotificationName:@"addcardback" object:nil];

}

然后在B中,

- (void)viewDidLoad {

    [super viewDidLoad];

   [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(back) name:@"addbabyback" object:nil];

}

- (void)dealloc

{

    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"addbabyback" object:nil];

    

}

-(void)back

{

    [self dismissViewControllerAnimated:YES completion:nil];

}

猜你喜欢

转载自blog.csdn.net/haoxuhong/article/details/82685569