iOS --- 获取屏幕顶层的UIViewController

经常会遇到一些场景, 要通过代码获取到当前显示在屏幕最顶层的UIViewController. 如何获取呢?

获取rootViewController

The root view controller provides the content view of the window. Assigning a view controller to this property (either programmatically or using Interface Builder) installs the view controller’s view as the content view of the window. If the window has an existing view hierarchy, the old views are removed before the new ones are installed.

rootViewController的设定通常会在设置keyWindow的时候遇到, 表示该UIWindow的最底层的UIViewController.

UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
UIViewController *rootViewController = keyWindow.rootViewController;

获取currentViewController

一般情况下, 可通过如下方式获取当前屏幕最顶层的ViewController:

- (UIViewController *)currentViewController {
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    UIViewController *vc = keyWindow.rootViewController;
    while (vc.presentedViewController) {
        vc = vc.presentedViewController;

        if ([vc isKindOfClass:[UINavigationController class]]) {
            vc = [(UINavigationController *)vc visibleViewController];
        } else if ([vc isKindOfClass:[UITabBarController class]]) {
            vc = [(UITabBarController *)vc selectedViewController];
        }
    }
    return vc;
}

你可能感兴趣的:(iOS --- 获取屏幕顶层的UIViewController)