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