美文网首页
获取当前viewcontroller,不论是push、prese

获取当前viewcontroller,不论是push、prese

作者: 那片阳光已醉 | 来源:发表于2018-03-01 17:42 被阅读112次

在项目中,我们经常性的使用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;

}

相关文章

网友评论

      本文标题:获取当前viewcontroller,不论是push、prese

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