IOS pop和present的区别

一、基本区别

pushViewController 导航控制器入栈的方式切换页面
presentViewController 模态切换的方式切换页面

二、对生命周期的影响
[self presentModalViewController:controller animated:YES];
self 不会调用dealloc自我销毁。
self.set 只会再第一次出现时调用ViewDidLoad加载,之后再执行该函数时只会调用:(void)viewWillAppear:(BOOL)animated;
[self dismissModalViewControllerAnimated:YES];
self 会调用dealloc
self之下的一个Controller会调用(void)viewWillAppear:(BOOL)animated;
[self.navigationController pushViewController:controller animated:YES];
上层的ViewController会调用viewdidload.
 [self.navigationController popViewControllerAnimated:YES];
上层的ViewController会调用dealloc
三、 A -> B -> C,在 C 中直接返回 A
3.1 用present实现的方法

C中返回事件 :

- (void)back  
{
    [self dismissModalViewControllerAnimated:NO]; // 注意一定是NO
    [[NSNotificationCenter  defaultCenter]postNotificationName:@"backback" object:nil];  
}

然后在B中 :

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(back) name:@"backback" object:nil];  
-(void)back  
{  
     [self dismissModalViewControllerAnimated:YES];  
}
3.2 pop的实现方法

返回到指定的控制器,要保证前面有入栈。

[self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:2] animated:YES];

也可以指定一个特定的控制器:

for (UIViewController *controller in self.navigationController.viewControllers) {
if ([controller isKindOfClass:[NeedBackViewController class]]) {
NeedBackViewController *vc = (NeedBackViewController *)controller;
[self.navigationController popToViewController:vc animated:YES];
}
}
四、判断当前是pop还是dismiss
4.1 通过判断self有没有present方式显示的父视图presentingViewController
- (IBAction)dismiss:(id)sender {
    if (self.presentingViewController) {
        [self dismissViewControllerAnimated:YES completion:nil];
    } else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}
4.2 通过判断self.navigationController.viewControllers的最后一个是否是当前控制器,或者self.navigationController.topViewController == self
- (IBAction)dismiss:(id)sender {
    if (self.navigationController.topViewController == self) {
        [self.navigationController popViewControllerAnimated:YES];
    } else {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • *7月8日上午 N:Block :跟一个函数块差不多,会对里面所有的内容的引用计数+1,想要解决就用__block...
    炙冰阅读 2,554评论 1 14
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,259评论 4 61
  • 1.自定义控件 a.继承某个控件 b.重写initWithFrame方法可以设置一些它的属性 c.在layouts...
    圍繞的城阅读 3,494评论 2 4
  • 当我快要迷糊的进入梦乡时,突然看到手机屏幕亮了。挣扎着艰难地爬起来,打开手机,我看到了小水的消息。 内容一般都很简...
    橘子味姑娘阅读 257评论 1 2
  • “买房!没有商量的余地!再等下去,连六环外的厕所都买不起了!” “我不想压力那么大,买了房什么也做不了...
    哨子声阅读 192评论 0 0