获取顶层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
.
|
网友评论