Last active
May 5, 2023 16:41
-
-
Save andresr-dev/a34524fadba2c949f3364f82754ef573 to your computer and use it in GitHub Desktop.
This is how to get the top view controller in swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var window: UIWindow? { | |
guard | |
let scene = UIApplication.shared.connectedScenes.first, | |
let sceneDelegate = scene.delegate as? UIWindowSceneDelegate, | |
let uiWindow = sceneDelegate.window | |
else { | |
return nil | |
} | |
return uiWindow | |
} | |
func topViewController(controller: UIViewController? = nil) -> UIViewController? { | |
let controller = controller ?? window?.rootViewController | |
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment