Sobes.tech
Junior — Middle

How can the active ViewController be determined in the current application context?

sobes.tech AI

Answer from AI

To determine the active (currently displayed) ViewController in an iOS application, you can traverse the hierarchy of controllers starting from the root view controller of the window.

Example of a Swift function that returns the current visible ViewController:

func getVisibleViewController(_ rootViewController: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
    if let nav = rootViewController as? UINavigationController {
        return getVisibleViewController(nav.visibleViewController)
    }
    if let tab = rootViewController as? UITabBarController {
        if let selected = tab.selectedViewController {
            return getVisibleViewController(selected)
        }
    }
    if let presented = rootViewController?.presentedViewController {
        return getVisibleViewController(presented)
    }
    return rootViewController
}

This function recursively checks:

  • Navigation controller — returns the visible controller in the stack.
  • Tab bar controller — returns the selected controller.
  • Modally presented controller — returns it.

Ultimately, it returns the ViewController that is currently displayed to the user.

How can the active ViewController be determined in… - sobes.tech