How to find topmost view controller on iOS

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

    Swift 4.2 Extension


    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
        }
    }
    

    Use it from anywhere like,

     UIApplication.topViewController()?.present(yourController, animated: true, completion: nil)
    

    or like,

     UIApplication.topViewController()?
                        .navigationController?
                        .popToViewController(yourController,
                                             animated: true)
    

    Fit to any classes like UINavigationController, UITabBarController

    Enjoy!

提交回复
热议问题