How to find topmost view controller on iOS

后端 未结 30 2975
遥遥无期
遥遥无期 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:14

    Simple extension for UIApplication in Swift:

    NOTE:

    It cares about moreNavigationController within UITabBarController

    extension UIApplication {
    
        class func topViewController(baseViewController: UIViewController? = UIApplication.sharedApplication().keyWindow?.rootViewController) -> UIViewController? {
    
            if let navigationController = baseViewController as? UINavigationController {
                return topViewController(navigationController.visibleViewController)
            }
    
            if let tabBarViewController = baseViewController as? UITabBarController {
    
                let moreNavigationController = tabBarViewController.moreNavigationController
    
                if let topViewController = moreNavigationController.topViewController where topViewController.view.window != nil {
                    return topViewController(topViewController)
                } else if let selectedViewController = tabBarViewController.selectedViewController {
                    return topViewController(selectedViewController)
                }
            }
    
            if let splitViewController = baseViewController as? UISplitViewController where splitViewController.viewControllers.count == 1 {
                return topViewController(splitViewController.viewControllers[0])
            }
    
            if let presentedViewController = baseViewController?.presentedViewController {
                return topViewController(presentedViewController)
            }
    
            return baseViewController
        }
    }
    

    Simple usage:

    if let topViewController = UIApplication.topViewController() {
        //do sth with top view controller
    }
    

提交回复
热议问题