Skip to content

Instantly share code, notes, and snippets.

@eMdOS
Created August 23, 2019 23:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eMdOS/80644fd91a13b78b4170eeae9f8dc034 to your computer and use it in GitHub Desktop.
Save eMdOS/80644fd91a13b78b4170eeae9f8dc034 to your computer and use it in GitHub Desktop.
Topmost view controller
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