swift 获取当前顶层控制器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
var topViewController: UIViewController? {
var resultVC: UIViewController?
resultVC = _topViewController(UIApplication.shared.keyWindow?.rootViewController)
while resultVC?.presentedViewController {
resultVC = _topViewController(resultVC?.presentedViewController)
}
return resultVC
}

func _topViewController(_ vc: UIViewController?) -> UIViewController? {
if (vc is UINavigationController) {
return _topViewController((vc as? UINavigationController)?.topViewController)
} else if (vc is UITabBarController) {
return _topViewController((vc as? UITabBarController)?.selectedViewController)
} else {
return vc
}
return nil
}