Skip to content

Instantly share code, notes, and snippets.

@rajubd49
Created July 10, 2018 09:55
Show Gist options
  • Save rajubd49/5ac7fa230c91a85216f8cacd0cb4f783 to your computer and use it in GitHub Desktop.
Save rajubd49/5ac7fa230c91a85216f8cacd0cb4f783 to your computer and use it in GitHub Desktop.
Get Top ViewController for iOS using Swift
extension UIApplication {
class func topViewController(base: UIViewController? = UIApplication.sharedApplication().keyWindow?.rootViewController) -> UIViewController? {
if let nav = base as? UINavigationController {
return topViewController(base: nav.visibleViewController)
}
if let tab = base as? UITabBarController {
if let selected = tab.selectedViewController {
return topViewController(base: selected)
}
}
if let presented = base?.presentedViewController {
return topViewController(base: presented)
}
return base
}
}
// USE IT LIKE,
if let topController = UIApplication.topViewController() {
topController.present(YourViewController, animated: true, completion: nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment