How to find topmost view controller on iOS

后端 未结 30 2846
遥遥无期
遥遥无期 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 08:55

    A complete non-recursive version, taking care of different scenarios:

    • The view controller is presenting another view
    • The view controller is a UINavigationController
    • The view controller is a UITabBarController

    Objective-C

     UIViewController *topViewController = self.window.rootViewController;
     while (true)
     {
         if (topViewController.presentedViewController) {
             topViewController = topViewController.presentedViewController;
         } else if ([topViewController isKindOfClass:[UINavigationController class]]) {
             UINavigationController *nav = (UINavigationController *)topViewController;
             topViewController = nav.topViewController;
         } else if ([topViewController isKindOfClass:[UITabBarController class]]) {
             UITabBarController *tab = (UITabBarController *)topViewController;
             topViewController = tab.selectedViewController;
         } else {
             break;
         }
     }
    

    Swift 4+

    extension UIWindow {
        func topViewController() -> UIViewController? {
            var top = self.rootViewController
            while true {
                if let presented = top?.presentedViewController {
                    top = presented
                } else if let nav = top as? UINavigationController {
                    top = nav.visibleViewController
                } else if let tab = top as? UITabBarController {
                    top = tab.selectedViewController
                } else {
                    break
                }
            }
            return top
        }
    }
    

提交回复
热议问题