寻找正在显示的视图控制器(最上层的视图控制器)

- (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;

    }

}

你可能感兴趣的:(寻找正在显示的视图控制器(最上层的视图控制器))