How to find topmost view controller on iOS

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

    Use below extension to grab current visible UIViewController. Worked for Swift 4.0 and later

    Swift 4.0 and Later:

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

    How to use?

    let objViewcontroller = UIApplication.topViewController()
    

提交回复
热议问题