Get top most UIViewController

后端 未结 24 2139
别那么骄傲
别那么骄傲 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:31

    For swift 4 / 5 + to get topmost viewController

    // MARK: UIApplication extensions
    
    extension UIApplication {
    
        class func getTopViewController(base: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
    
            if let nav = base as? UINavigationController {
                return getTopViewController(base: nav.visibleViewController)
    
            } else if let tab = base as? UITabBarController, let selected = tab.selectedViewController {
                return getTopViewController(base: selected)
    
            } else if let presented = base?.presentedViewController {
                return getTopViewController(base: presented)
            }
            return base
        }
    }
    

    How to use

    if let topVC = UIApplication.getTopViewController() {
       topVC.view.addSubview(forgotPwdView)
    }
    

提交回复
热议问题