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

后端 未结 14 1688
小蘑菇
小蘑菇 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 01:03

    This is an improved version of @ProgrammierTier's answer. If you have a navbar nested in a tabbar, you will get back UINavigationController using @ProgrammierTier's answer. Also, there is less force unwrapping. This should address the issue @Harendra-Tiwari is facing.

    Swift 4.2:

    func getVisibleViewController(_ rootViewController: UIViewController?) -> UIViewController? {
    
      var rootVC = rootViewController
      if rootVC == nil {
          rootVC = UIApplication.shared.keyWindow?.rootViewController
      }
    
      var presented = rootVC?.presentedViewController
      if rootVC?.presentedViewController == nil {
          if let isTab = rootVC?.isKind(of: UITabBarController.self), let isNav = rootVC?.isKind(of: UINavigationController.self) {
              if !isTab && !isNav {
                  return rootVC
              }
              presented = rootVC
          } else {
              return rootVC
          }
      }
    
      if let presented = presented {
        if presented.isKind(of: UINavigationController.self) {
            if let navigationController = presented as? UINavigationController {
                return navigationController.viewControllers.last!
            }
         }
    
         if presented.isKind(of: UITabBarController.self) {
            if let tabBarController = presented as? UITabBarController {
                if let navigationController = tabBarController.selectedViewController! as? UINavigationController {
                     return navigationController.viewControllers.last!
                 } else {
                     return tabBarController.selectedViewController!
                 }
             }
         }
    
         return getVisibleViewController(presented)
      }
      return nil
    }
    

提交回复
热议问题