Getting the top most UIViewController

后端 未结 3 1441
不思量自难忘°
不思量自难忘° 2021-02-01 00:35

If I push view controllers and/or present modal view controllers on a UINavigationController, how can I find out what is the top most UIViewController?

相关标签:
3条回答
  • 2021-02-01 01:20

    I know the question is old, but it's still popular - that's why I'd like to post my best solution which handles different UIViewController's subclasses. At the same time you can extend functionality of this method by your custom "collection" controllers such as side menu.

    extension UIWindow {
    
      var visibleViewController: UIViewController? {
        guard let rootViewController = rootViewController else {
          return nil
        }
        return visibleViewController(for: rootViewController)
      }
    
      private func visibleViewController(for controller: UIViewController) -> UIViewController {
        var nextOnStackViewController: UIViewController? = nil
        if let presented = controller.presentedViewController {
          nextOnStackViewController = presented
        } else if let navigationController = controller as? UINavigationController,
          let visible = navigationController.visibleViewController {
          nextOnStackViewController = visible
        } else if let tabBarController = controller as? UITabBarController,
          let visible = (tabBarController.selectedViewController ??
            tabBarController.presentedViewController) {
          nextOnStackViewController = visible
        }
    
        if let nextOnStackViewController = nextOnStackViewController {
          return visibleViewController(for: nextOnStackViewController)
        } else {
          return controller
        }
      }
    
    }
    
    0 讨论(0)
  • 2021-02-01 01:25

    You want visibleViewController:

    The currently visible view can belong either to the view controller at the top of the navigation stack or to a view controller that was presented modally.

    0 讨论(0)
  • 2021-02-01 01:30
    NSArray *viewContrlls=[[self navigationController] viewControllers];
    
    [viewContrlls lastObject];
    
    0 讨论(0)
提交回复
热议问题