Created
June 30, 2019 11:05
-
-
Save florentmorin/f1cf8ee69fdf8e8ef8f871ca27433ca0 to your computer and use it in GitHub Desktop.
Top Most View Controller in UIKit
This file contains 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
import UIKit | |
extension UIViewController { | |
/// Top most view controller in view hierarchy | |
var topMostViewController: UIViewController { | |
// No presented view controller? Current controller is the most view controller | |
guard let presentedViewController = self.presentedViewController else { | |
return self | |
} | |
// Presenting a navigation controller? | |
// Top most view controller is in visible view controller hierarchy | |
if let navigation = presentedViewController as? UINavigationController { | |
if let visibleController = navigation.visibleViewController { | |
return visibleController.topMostViewController | |
} else { | |
return navigation.topMostViewController | |
} | |
} | |
// Presenting a tab bar controller? | |
// Top most view controller is in visible view controller hierarchy | |
if let tabBar = presentedViewController as? UITabBarController { | |
if let selectedTab = tabBar.selectedViewController { | |
return selectedTab.topMostViewController | |
} else { | |
return tabBar.topMostViewController | |
} | |
} | |
// Presenting another kind of view controller? | |
// Top most view controller is in visible view controller hierarchy | |
return presentedViewController.topMostViewController | |
} | |
} | |
extension UIWindow { | |
/// Top most view controller in view hierarchy | |
/// - Note: Wrapper to UIViewController.topMostViewController | |
var topMostViewController: UIViewController? { | |
return self.rootViewController?.topMostViewController | |
} | |
} | |
extension UIApplication { | |
/// Top most view controller in view hierarchy | |
/// - Note: Wrapper to UIWindow.topMostViewController | |
var topMostViewController: UIViewController? { | |
return self.keyWindow?.topMostViewController | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment