Get the top most UIViewController
suggest changeA common approach to get the topmost UIViewController is to start at the root view controller of the active UIWindow. keyWindow is nil for a scene-based app, and return base! crashes when base is nil. The extension was missing its closing brace.
extension UIApplication {
func topViewController(_ base: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController {
if let nav = base as? UINavigationController {
return topViewController(nav.visibleViewController)
}
if let tab = base as? UITabBarController {
if let selected = tab.selectedViewController {
return topViewController(selected)
}
}
if let presented = base?.presentedViewController {
return topViewController(presented)
}
return base!
}
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents