美文网首页
iOS获取最顶层ViewController

iOS获取最顶层ViewController

作者: flionel | 来源:发表于2018-11-01 11:32 被阅读19次

    获取顶层ViewController的代码如下,

    extension UIViewController {
        var currentViewController: UIViewController? {
            var topVC = UIApplication.shared.keyWindow?.rootViewController
            while topVC?.presentedViewController != nil {
                topVC = _getTopViewController(vc: topVC)
            }
            return topVC
        }
    
        fileprivate func _getTopViewController(vc: UIViewController?) -> UIViewController? {
            guard let temp = vc else { return nil }
            if temp.isKind(of: UINavigationController.self) {
                let naviVC = temp as! UINavigationController
                return _getTopViewController(vc: naviVC.topViewController)
            } else if temp.isKind(of: UITabBarController.self) {
                let tabVC = temp as! UITabBarController
                return _getTopViewController(vc: tabVC.selectedViewController)
            } else {
                return vc
            }
        }
    }
    

    The view controller that is presented by this view controller, or one of its ancestors in the view controller hierarchy.

    When you present a view controller modally (either explicitly or implicitly) using the present(_:animated:completion:) method, the view controller that called the method has this property set to the view controller that it presented. If the current view controller did not present another view controller modally, the value in this property is nil.

    |

    相关文章

      网友评论

          本文标题:iOS获取最顶层ViewController

          本文链接:https://www.haomeiwen.com/subject/rtwtxqtx.html