美文网首页专注iOS开发IOS收藏iOS OC 学习手册
iOS判断当前ViewController是push还是pres

iOS判断当前ViewController是push还是pres

作者: plantseeds | 来源:发表于2016-10-28 21:21 被阅读7619次

    我本来试用方法:

    - (IBAction)dismiss:(id)sender {
        if ([self respondsToSelector:@selector(dismissViewControllerAnimated:completion:)]) {
            //判断1
            [self dismissViewControllerAnimated:YES completion:nil];
        } else if ([self.navigationController respondsToSelector:@selector(popViewControllerAnimated:)]) {
            //判断2
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
    

    结果发现不管是push或present,都只进判断1,不进判断2.
    于是google,

    方法一:

    通过判断self有没有present方式显示的父视图presentingViewController

    - (IBAction)dismiss:(id)sender {
        if (self.presentingViewController) {
            [self dismissViewControllerAnimated:YES completion:nil];
        } else {
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
    
    方法二:

    通过判断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];
        }
    }
    

    相关文章

      网友评论

      • CoderLocus:方法一有个bug,就是第一个界面present的,之后都push。在后面的界面也会误判成present,所以方法一需要加一些判断:
        if (self.presentingViewController && self.navigationController.viewControllers.count == 1) {
        [self dismissViewControllerAnimated:YES completion:nil];
        } else {
        [self.navigationController popViewControllerAnimated:YES];
        }
      • RiberWang:在present之前加上一个导航控制器的话 方法二确实是不可用的,因为必走if语句
      • footSInRoad: 谢谢分享 我试了 方法一可以 方法二 不好用

      本文标题:iOS判断当前ViewController是push还是pres

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