How to find topmost view controller on iOS

后端 未结 30 2901
遥遥无期
遥遥无期 2020-11-22 08:40

I\'ve run into a couple of cases now where it would be convenient to be able to find the \"topmost\" view controller (the one responsible for the current view), but haven\'t

30条回答
  •  天涯浪人
    2020-11-22 09:08

    I know its very late and might be redundant. But following is the snippet I came up with which is working for me :

        static func topViewController() -> UIViewController? {
            return topViewController(vc: UIApplication.shared.keyWindow?.rootViewController)
        }
    
        private static func topViewController(vc:UIViewController?) -> UIViewController? {
            if let rootVC = vc {
                guard let presentedVC = rootVC.presentedViewController else {
                    return rootVC
                }
                if let presentedNavVC = presentedVC as? UINavigationController {
                    let lastVC = presentedNavVC.viewControllers.last
                    return topViewController(vc: lastVC)
                }
                return topViewController(vc: presentedVC)
            }
            return nil
        }
    

提交回复
热议问题