美文网首页
iOS获取顶层控制器

iOS获取顶层控制器

作者: 黄定师 | 来源:发表于2019-06-26 11:17 被阅读0次

前言

在项目中经常需要获取当前顶层控制器,然后去完成某些操作。这里记录下我的实现方式。


代码实现

方式一

+ (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 *navigationController = (UINavigationController *)rootViewController;
        return [self topViewControllerWithRootViewController:navigationController.visibleViewController];
    } else if (rootViewController.presentedViewController) {
        UIViewController *presentedViewController = rootViewController.presentedViewController;
        return [self topViewControllerWithRootViewController:presentedViewController];
    } else {
        return rootViewController;
    }
}

方式二

- (UIViewController *)topController {
    UIViewController *viewController = self;
    while (1) {
        if (self.presentedViewController) {
            viewController = self.presentedViewController;
        } else if ([self isKindOfClass:[UINavigationController class]]) {
            UINavigationController* navigationController = (UINavigationController* )viewController;
            viewController = [navigationController.childViewControllers lastObject];
        } else if ([viewController isKindOfClass:[UITabBarController class]]) {
            UITabBarController* tabBarController = (UITabBarController* )viewController;
            viewController = tabBarController.selectedViewController;
        } else {
            NSUInteger childViewControllerCount = viewController.childViewControllers.count;
            if (childViewControllerCount > 0) {
                viewController = viewController.childViewControllers.lastObject;
                return viewController;
            } else {
                return viewController;
            }
        }
    }
    return viewController;
}

相关文章

网友评论

      本文标题:iOS获取顶层控制器

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