获取当前viewcontroller,不论是push、present进来的控制器

在项目中,我们经常性的使用present和push联合跳转页面,但是有的时候会跳的找不到当前的viewcontroller了,下面的方法可以有效解决


#pragma mark ************** 获取当前屏幕显示的viewcontroller ************** shutong **

- (UIViewController *)getCurrentVC

{

    //获取到当前的根控制器

    UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;



    UIViewController *currentVC = [self getCurrentVCFrom:rootViewController];



    return currentVC;

}

- (UIViewController *)getCurrentVCFrom:(UIViewController *)rootVC

{

    UIViewController *currentVC;



    if ([rootVC presentedViewController]) {

        // 视图是被presented出来的



        rootVC = [rootVC presentedViewController];

    }



    if ([rootVC isKindOfClass:[UITabBarController class]]) {

        // 根视图为UITabBarController



        currentVC = [self getCurrentVCFrom:[(UITabBarController *)rootVC selectedViewController]];



    } else if ([rootVC isKindOfClass:[UINavigationController class]]){

        // 根视图为UINavigationController



        currentVC = [self getCurrentVCFrom:[(UINavigationController *)rootVC visibleViewController]];



    } else {

        // 根视图为非导航类



        currentVC = rootVC;

    }



    return currentVC;

}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,446评论 25 708
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,250评论 4 61
  • 最能洞察的呼吸 毫无止境 看 远处山在飞 试想放眼出去的是雾 喧嚣的公路奔洒的咖啡 一杯浓缩的想象 清醒的我 在飞...
    麾毛杆儿阅读 146评论 0 0
  • 今天凌晨1点多苹果发布了苹果X,然而面对苹果更新换代的速度,我们的工作质量也被迫应该逐步提高,不然你就赶不上科技...
    colapc阅读 209评论 0 0
  • 这个世界所有的东西都是有味道的。 小七对味道特别敏感,她喜欢自己觉得好闻的味道。 高中的时候,她喜欢原味的东西。总...
    老斯基酱阅读 402评论 0 0