Did you see this one (at the end of the thread) ?
https://stackoverflow.com/questions/26667009/get-top-most-uiviewcontroller
I copy the answer here:
extension UIApplication {
func topViewController() -> UIViewController? {
var topViewController: UIViewController? = nil
if #available(iOS 13, *) {
for scene in connectedScenes {
if let windowScene = scene as? UIWindowScene {
for window in windowScene.windows {
if window.isKeyWindow {
topViewController = window.rootViewController
}
}
}
}
} else {
topViewController = keyWindow?.rootViewController
}
while true {
if let presented = topViewController?.presentedViewController {
topViewController = presented
} else if let navController = topViewController as? UINavigationController {
topViewController = navController.topViewController
} else if let tabBarController = topViewController as? UITabBarController {
topViewController = tabBarController.selectedViewController
} else {
// Handle any other third party container in `else if` if required
break
}
}
return topViewController
}
}
// It could be used in this way:
let topController = UIApplication.shared.topViewController()
topController?.present(controllerToPresent, animated: true, completion: nil)
If you don't need iOS < 13, you can remove the call to keywindow.
Hope that works for you.
Topic:
UI Frameworks
SubTopic:
UIKit
Tags: