Clicky

iOS Dev Nugget 251 Retrieving the Current View Controller

.

Need to run a code review on your codebase? Hire me

During development, I often want to retrieve the view controller that is currently displayed. This is rather vague — it could mean the view controller at the top of the stack of the current UINavigationController, the currently presented view controller, etc. So I wrote this function which figures it out most of the time:

func currentViewController(_ viewController: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
    guard let viewController = viewController else { return nil }

    if let viewController = viewController as? UINavigationController {
        if let viewController = viewController.visibleViewController {
            return currentViewController(viewController)
        } else {
            return currentViewController(viewController.topViewController)
        }
    } else if let viewController = viewController as? UITabBarController {
        if let viewControllers = viewController.viewControllers, viewControllers.count > 5, viewController.selectedIndex >= 4 {
            return currentViewController(viewController.moreNavigationController)
        } else {
            return currentViewController(viewController.selectedViewController)
        }
    } else if let viewController = viewController.presentedViewController {
        return viewController
    } else if viewController.childViewControllers.count > 0 {
        return viewController.childViewControllers[0]
    } else {
        return viewController
    }
}

Call it with:

currentViewController()

Your feedback is valuable: Do you want more nuggets like this?   Yes   or   No

.

.

Like this and want such iOS dev nuggets to be emailed to you, weekly?

Sign Me Up! or follow @iosdevnuggets on Twitter

.

View archives of past issues