Get the current view controller from the app delegate

前端 未结 11 1952
悲哀的现实
悲哀的现实 2020-11-30 22:46

i am new to ios. I need to know the current view controller from app delegate.. i have no idea about this and i don\'t knowto implement this. i am using this code toimplemn

11条回答
  •  渐次进展
    2020-11-30 23:00

    Swift version of jjv360's great answer, (I got rid of some redundant returns, and I think Swift is more readable)

    func getCurrentViewController(_ vc: UIViewController) -> UIViewController? {
        if let pvc = vc.presentedViewController {
            return getCurrentViewController(pvc)
        }
        else if let svc = vc as? UISplitViewController, svc.viewControllers.count > 0 {
            return getCurrentViewController(svc.viewControllers.last!)
        }
        else if let nc = vc as? UINavigationController, nc.viewControllers.count > 0 {
            return getCurrentViewController(nc.topViewController!)
        }
        else if let tbc = vc as? UITabBarController {
            if let svc = tbc.selectedViewController {
                return getCurrentViewController(svc)
            }
        }
        return vc
    }
    

    From you AppDelegate,

        guard let rvc = self.window?.rootViewController else {
            return
        }
        if let vc = getCurrentViewController(rvc) {
            // do your stuff here
        }
    

提交回复
热议问题