Created
July 28, 2019 07:09
-
-
Save ppth0608/7a5b1d020245610046e4da709edb722f to your computer and use it in GitHub Desktop.
How to find `topMostViewController`
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
import UIKit | |
extension UIViewController { | |
class var rootTabBarController: TabBarController? { | |
guard let keyWindow = UIApplication.shared.keyWindow else { return nil } | |
return keyWindow.rootViewController as? TabBarController | |
} | |
class var topMost: UIViewController? { | |
guard let keyWindow = UIApplication.shared.keyWindow else { return nil } | |
return self.topMost(of: keyWindow.rootViewController) | |
} | |
class func topMost(of viewController: UIViewController?) -> UIViewController? { | |
// presented view controller | |
if let presentedViewController = viewController?.presentedViewController { | |
return self.topMost(of: presentedViewController) | |
} | |
// UITabBarController | |
if let tabBarController = viewController as? UITabBarController, | |
let selectedViewController = tabBarController.selectedViewController { | |
return self.topMost(of: selectedViewController) | |
} | |
// UINavigationController | |
if let navigationController = viewController as? UINavigationController, | |
let visibleViewController = navigationController.visibleViewController { | |
return self.topMost(of: visibleViewController) | |
} | |
// UIPageController | |
if let pageViewController = viewController as? UIPageViewController, | |
pageViewController.viewControllers?.count == 1 { | |
return self.topMost(of: pageViewController.viewControllers?.first) | |
} | |
// child view controller | |
for subview in viewController?.view?.subviews ?? [] { | |
if let childViewController = subview.next as? UIViewController { | |
return self.topMost(of: childViewController) | |
} | |
} | |
return viewController | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment