How to find topmost view controller on iOS

后端 未结 30 2370
遥遥无期
遥遥无期 2020-11-22 08:40

I\'ve run into a couple of cases now where it would be convenient to be able to find the \"topmost\" view controller (the one responsible for the current view), but haven\'t

30条回答
  •  逝去的感伤
    2020-11-22 09:00

    This answer includes childViewControllers and maintains a clean and readable implementation.

    + (UIViewController *)topViewController
    {
        UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
    
        return [rootViewController topVisibleViewController];
    }
    
    - (UIViewController *)topVisibleViewController
    {
        if ([self isKindOfClass:[UITabBarController class]])
        {
            UITabBarController *tabBarController = (UITabBarController *)self;
            return [tabBarController.selectedViewController topVisibleViewController];
        }
        else if ([self isKindOfClass:[UINavigationController class]])
        {
            UINavigationController *navigationController = (UINavigationController *)self;
            return [navigationController.visibleViewController topVisibleViewController];
        }
        else if (self.presentedViewController)
        {
            return [self.presentedViewController topVisibleViewController];
        }
        else if (self.childViewControllers.count > 0)
        {
            return [self.childViewControllers.lastObject topVisibleViewController];
        }
    
        return self;
    }
    

提交回复
热议问题