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

后端 未结 14 1667
小蘑菇
小蘑菇 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

    @aviatorken89's answer worked well for me. I had to translate it to Swift - for anybody starting out with Swift:

    Updated for Swift 3:

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

    Old answer:

    func applicationWillResignActive(application: UIApplication) {
        let currentViewController = getVisibleViewController(nil)
    }
    
    func getVisibleViewController(var rootViewController: UIViewController?) -> UIViewController? {
    
        if rootViewController == nil {
            rootViewController = UIApplication.sharedApplication().keyWindow?.rootViewController
        }
    
        if rootViewController?.presentedViewController == nil {
            return rootViewController
        }
    
        if let presented = rootViewController?.presentedViewController {
            if presented.isKindOfClass(UINavigationController) {
                let navigationController = presented as! UINavigationController
                return navigationController.viewControllers.last!
            }
    
            if presented.isKindOfClass(UITabBarController) {
                let tabBarController = presented as! UITabBarController
                return tabBarController.selectedViewController!
            }
    
            return getVisibleViewController(presented)
        }
        return nil
    }
    

提交回复
热议问题