Created
August 23, 2019 23:11
-
-
Save eMdOS/80644fd91a13b78b4170eeae9f8dc034 to your computer and use it in GitHub Desktop.
Topmost view controller
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 | |
public extension UIApplication { | |
/// Returns the topmost view controller in the hierarchy of the given view controller. | |
/// | |
/// If no parameter passed, by default the function takes the root view controller set for the key window in the application. | |
/// | |
/// ```swift | |
/// UIApplication.shared.keyWindow?.rootViewController | |
/// ``` | |
/// | |
/// - Parameter rootViewController: The root view controller | |
/// - Returns: The topmost view controller | |
func topViewController( | |
for rootViewController: UIViewController? = UIApplication.shared.keyWindow?.rootViewController | |
) -> UIViewController? { | |
guard let rootViewController = rootViewController else { | |
return .none | |
} | |
if let navigationController = rootViewController as? UINavigationController { | |
return topViewController(for: navigationController.viewControllers.last) | |
} | |
if let tabbarController = rootViewController as? UITabBarController { | |
return topViewController(for: tabbarController.selectedViewController) | |
} | |
if let presentedViewController = rootViewController.presentedViewController { | |
return topViewController(for: presentedViewController) | |
} | |
return rootViewController | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment