Created
July 10, 2018 09:55
-
-
Save rajubd49/5ac7fa230c91a85216f8cacd0cb4f783 to your computer and use it in GitHub Desktop.
Get Top ViewController for iOS using Swift
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
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