Get top most UIViewController

后端 未结 24 1879
别那么骄傲
别那么骄傲 2020-11-22 14:47

I can\'t seem to get the top most UIViewController without access to a UINavigationController. Here is what I have so far:

UIApplic         


        
24条回答
  •  抹茶落季
    2020-11-22 15:26

    extension UIWindow {
    
        func visibleViewController() -> UIViewController? {
            if let rootViewController: UIViewController = self.rootViewController {
                return UIWindow.getVisibleViewControllerFrom(vc: rootViewController)
            }
            return nil
        }
    
        static func getVisibleViewControllerFrom(vc:UIViewController) -> UIViewController {
            if let navigationController = vc as? UINavigationController,
                let visibleController = navigationController.visibleViewController  {
                return UIWindow.getVisibleViewControllerFrom( vc: visibleController )
            } else if let tabBarController = vc as? UITabBarController,
                let selectedTabController = tabBarController.selectedViewController {
                return UIWindow.getVisibleViewControllerFrom(vc: selectedTabController )
            } else {
                if let presentedViewController = vc.presentedViewController {
                    return UIWindow.getVisibleViewControllerFrom(vc: presentedViewController)
                } else {
                    return vc
                }
            }
        }
    }
    

    Usage:

    if let topController = window.visibleViewController() {
        println(topController)
    }
    

提交回复
热议问题