iPhone - 如何找到最顶层的视图控制器

- (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 *navigationController = (UINavigationController*)rootViewController;

        return [self topViewControllerWithRootViewController:navigationController.visibleViewController];

    }

    else if (rootViewController.presentedViewController) {

        UIViewController* presentedViewController = rootViewController.presentedViewController;

        return [self topViewControllerWithRootViewController:presentedViewController];

    }

    else {

        return rootViewController;

    }

}

你可能感兴趣的:(基础知识点,iphone,ios)