Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save michaeldong/cc9ff01293148b0d19bc6199545a46e7 to your computer and use it in GitHub Desktop.

Select an option

Save michaeldong/cc9ff01293148b0d19bc6199545a46e7 to your computer and use it in GitHub Desktop.
import UIKit
extension UIApplication {
class func topViewController(_ base: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
if let navigationController = base as? UINavigationController, navigationController.viewControllers.count > 0 {
return topViewController(navigationController.visibleViewController)
}
if let tabBarController = base as? UITabBarController {
if let selected = tabBarController.selectedViewController {
return topViewController(selected)
}
}
if let presentedViewController = base?.presentedViewController {
return topViewController(presentedViewController)
}
return base
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment