Skip to content

Instantly share code, notes, and snippets.

@pablogm
Last active May 30, 2018 09:54
Show Gist options
  • Save pablogm/d4cb926fe419687a8fc5 to your computer and use it in GitHub Desktop.
Save pablogm/d4cb926fe419687a8fc5 to your computer and use it in GitHub Desktop.
Swift UIApplication utils: Get the top view controller
//
// UIApplication+Utils.swift
// Swift Utils
//
import Foundation
extension UIApplication {
class func topViewController(base: UIViewController? = (UIApplication.sharedApplication().delegate as! AppDelegate).window?.rootViewController) -> UIViewController? {
if let nav = base as? UINavigationController {
return topViewController(nav.visibleViewController)
}
if let tab = base as? UITabBarController {
if let selected = tab.selectedViewController {
return topViewController(selected)
}
}
if let presented = base?.presentedViewController {
return topViewController(presented)
}
return base
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment