美文网首页
寻找最外层的控制器、最上层控制器

寻找最外层的控制器、最上层控制器

作者: 张家杰仔 | 来源:发表于2017-04-06 10:41 被阅读25次
    //寻找最外层控制器
    - (UIViewController *)keyVc {
        UIViewController *rootVc = [UIApplication sharedApplication].keyWindow.rootViewController;
        UIViewController *keyVc = rootVc;
        while ([keyVc presentedViewController]) {
            keyVc = [keyVc presentedViewController];
        }
        return keyVc;
    }
    
    
    //寻找最上层控制器
    - (UIViewController*)topViewController {
        return [self topViewControllerWithRootViewController:[UIApplication sharedApplication].keyWindow.rootViewController];
    }
    - (UIViewController*)topViewControllerWithRootViewController:(UIViewController*)rootViewController {
        if ([rootViewController isKindOfClass:[UITabBarController class]]) {
            UITabBarController* tabBarController = (UITabBarController*)rootViewController;
            return [self topViewControllerWithRootViewController:tabBarController.selectedViewController];
        } else if ([rootViewController isKindOfClass:[UINavigationController class]]) {
            UINavigationController* nav = (UINavigationController*)rootViewController;
            return [self topViewControllerWithRootViewController:nav.visibleViewController];
        } else if (rootViewController.presentedViewController) {
            UIViewController* presentedViewController = rootViewController.presentedViewController;
            return [self topViewControllerWithRootViewController:presentedViewController];
        } else {
            return rootViewController;
        }
    }
    

    相关文章

      网友评论

          本文标题:寻找最外层的控制器、最上层控制器

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