Get top most UIViewController

后端 未结 24 2148
别那么骄傲
别那么骄傲 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条回答
  •  萌比男神i
    2020-11-22 15:34

    have this extension

    Swift 2.*

    extension UIApplication {
        class func topViewController(controller: UIViewController? = UIApplication.sharedApplication().keyWindow?.rootViewController) -> UIViewController? {
            if let navigationController = controller as? UINavigationController {
                return topViewController(navigationController.visibleViewController)
            }
            if let tabController = controller as? UITabBarController {
                if let selected = tabController.selectedViewController {
                    return topViewController(selected)
                }
            }
            if let presented = controller?.presentedViewController {
                return topViewController(presented)
            }
            return controller
        }
    }
    

    Swift 3

    extension UIApplication {
        class func topViewController(controller: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
            if let navigationController = controller as? UINavigationController {
                return topViewController(controller: navigationController.visibleViewController)
            }
            if let tabController = controller as? UITabBarController {
                if let selected = tabController.selectedViewController {
                    return topViewController(controller: selected)
                }
            }
            if let presented = controller?.presentedViewController {
                return topViewController(controller: presented)
            }
            return controller
        }
    }
    

    You can you use this anywhere on your controller

    if let topController = UIApplication.topViewController() {
    
    }
    

提交回复
热议问题