Get current view controller from the app delegate

2019-01-17 13:25发布

I know that to get the current view controller from the app delegate, I can use the navigationController property I have set up for my app. However, it's possible in many places throughout my app that a modal navigation controller could have been presented. Is there any way to detect this from the app delegate, since the current navigation controller will be different from the one to which the app delegate holds a reference?

10条回答
小情绪 Triste *
2楼-- · 2019-01-17 13:48

This worked for me. I have many targets that have different controllers so previous answers didn't seemed to work.

first you want this inside your AppDelegate class:

var window: UIWindow?

then, in your function

let navigationController = window?.rootViewController as? UINavigationController
if let activeController = navigationController!.visibleViewController {
    if activeController.isKindOfClass( MyViewController )  {
        println("I have found my controller!")    
   }
}
查看更多
干净又极端
3楼-- · 2019-01-17 13:49

In swift you can get the active ViewController like this :

 let navigationController = application.windows[0].rootViewController as UINavigationController

 let activeViewCont = navigationController.visibleViewController
查看更多
【Aperson】
4楼-- · 2019-01-17 13:50

If you have the navigation controller in the App Delegate, just use the visibleViewController property. It will give you the visible controller, even if it's a modal.

查看更多
啃猪蹄的小仙女
5楼-- · 2019-01-17 13:53

The best solution, works also with moreNavigationController in UITabBarController:

extension UIApplication {
    class func topViewController(base: UIViewController? = UIApplication.sharedApplication().keyWindow?.rootViewController) -> UIViewController? {

        if let nav = base as? UINavigationController {
            return topViewController(nav.visibleViewController)
        }

        if let tab = base as? UITabBarController {
            let moreNavigationController = tab.moreNavigationController

            if let top = moreNavigationController.topViewController  where top.view.window != nil {
                return topViewController(top)
            } else if let selected = tab.selectedViewController {
                return topViewController(selected)
            }
        }

        if let presented = base?.presentedViewController {
            return topViewController(presented)
        }

        return base
    }
}
查看更多
登录 后发表回答