Skip to content

Instantly share code, notes, and snippets.

@igrechuhin
Forked from snikch/gist:3661188
Last active August 29, 2015 14:14
Show Gist options
  • Save igrechuhin/3dbb627e9a2c35e9a9e4 to your computer and use it in GitHub Desktop.
Save igrechuhin/3dbb627e9a2c35e9a9e4 to your computer and use it in GitHub Desktop.
Swift:
extension UIWindow {
func visibleViewController() -> UIViewController? {
if let rootViewController: UIViewController = self.rootViewController {
return UIWindow.getVisibleViewControllerFrom(rootViewController)
}
return nil
}
class func getVisibleViewControllerFrom(vc:UIViewController) -> UIViewController {
if vc.isKindOfClass(UINavigationController.self) {
let navigationController = vc as UINavigationController
return UIWindow.getVisibleViewControllerFrom( navigationController.visibleViewController)
} else if vc.isKindOfClass(UITabBarController.self) {
let tabBarController = vc as UITabBarController
return UIWindow.getVisibleViewControllerFrom(tabBarController.selectedViewController!)
} else {
if let presentedViewController = vc.presentedViewController {
return UIWindow.getVisibleViewControllerFrom(presentedViewController.presentedViewController!)
} else {
return vc;
}
}
}
Usage:
if let topController = window.visibleViewController() {
println(topController)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment