Created
June 26, 2024 15:55
-
-
Save CocoaBob/7b0a13fd03580899166e0448aba47ab6 to your computer and use it in GitHub Desktop.
Swift get top view controller
This file contains hidden or 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
// MARK: Find top view controller | |
extension UIViewController { | |
func topViewController(_ base: UIViewController?, _ nonPresented: Bool = false) -> UIViewController? { | |
if let nav = base as? UINavigationController { | |
return topViewController(nav.visibleViewController, nonPresented) | |
} | |
if let tab = base as? UITabBarController { | |
if let selected = tab.selectedViewController { | |
return topViewController(selected, nonPresented) | |
} | |
} | |
if let presented = base?.presentedViewController { | |
return topViewController(presented, nonPresented) | |
} | |
if let searchController = base as? UISearchController { | |
return topViewController(searchController.searchResultsController, nonPresented) | |
} | |
if nonPresented, let presentingVC = base?.presentingViewController { | |
return presentingVC | |
} else { | |
return base | |
} | |
} | |
func topViewController(_ nonPresented: Bool = false) -> UIViewController? { | |
return topViewController(self, nonPresented) | |
} | |
class func topViewController(_ nonPresented: Bool = false) -> UIViewController? { | |
return UIViewController.root?.topViewController(nonPresented) | |
} | |
static var root: UIViewController? { | |
return UIApplication.shared.mainWindow?.rootViewController | |
} | |
} | |
extension UIApplication { | |
var mainWindow: UIWindow? { | |
if #available(iOS 13.0, *) { | |
return UIApplication | |
.shared | |
.connectedScenes | |
.flatMap { ($0 as? UIWindowScene)?.windows ?? [] } | |
.last { $0.isKeyWindow } | |
} else { | |
return UIApplication.shared.keyWindow | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment