How to get visible viewController from app delegate when using storyboard?

后端 未结 14 1705
小蘑菇
小蘑菇 2020-12-05 00:14

I have some viewControllers, and I don\'t use NavigationController. How can I get visible view controller in app delegate methods (e.g. appli

14条回答
  •  孤街浪徒
    2020-12-05 00:59

    Here is an answer in Swift 4 that is very similar to the accepted answer but has a few improvements:

    1. Iterative instead of recursive.
    2. Goes all the way does the navigation stack.
    3. More "swifty" syntax.
    4. Static variable that can be put anywhere (not just in AppDelegate).
    5. Won't crash in odd cases, i.e. when a tab bar controller has no selected view controller.

      static var visibleViewController: UIViewController? {
          var currentVc = UIApplication.shared.keyWindow?.rootViewController
          while let presentedVc = currentVc?.presentedViewController {
              if let navVc = (presentedVc as? UINavigationController)?.viewControllers.last {
                  currentVc = navVc
              } else if let tabVc = (presentedVc as? UITabBarController)?.selectedViewController {
                  currentVc = tabVc
              } else {
                  currentVc = presentedVc
              }
          }
          return currentVc
      }
      

提交回复
热议问题