Last active
December 6, 2021 01:29
-
-
Save liuzhida33/0c9f97a0a89fef76b613c77e233e7467 to your computer and use it in GitHub Desktop.
Get TopMostController of UIViewController
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
import UIKit | |
extension UIViewController { | |
static var rootViewController: UIViewController? { | |
guard let keyWindow = UIApplication.shared.delegate?.window ?? UIApplication.shared.windows.first(where: { $0.isKeyWindow && $0.rootViewController != nil }) else { return nil } | |
return keyWindow.rootViewController | |
} | |
static var topMostController: UIViewController? { | |
return topMost(of: rootViewController) | |
} | |
private static func topMost(of viewController: UIViewController?) -> UIViewController? { | |
// presented view controller | |
if let presentedViewController = viewController?.presentedViewController { | |
return topMost(of: presentedViewController) | |
} | |
// UITabBarController | |
if let tabBarController = viewController as? UITabBarController, | |
let selectedViewController = tabBarController.selectedViewController { | |
return topMost(of: selectedViewController) | |
} | |
// UINavigationController | |
if let navigationController = viewController as? UINavigationController, | |
let visibleViewController = navigationController.visibleViewController { | |
return topMost(of: visibleViewController) | |
} | |
// UIPageController | |
if let pageViewController = viewController as? UIPageViewController, | |
pageViewController.viewControllers?.count == 1 { | |
return topMost(of: pageViewController.viewControllers?.first) | |
} | |
// child view controller | |
for subview in viewController?.view?.subviews ?? [] { | |
if let childViewController = subview.next as? UIViewController { | |
return topMost(of: childViewController) | |
} | |
} | |
return viewController | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment