swift查找当前ViewVontroller
2018-07-20 本文已影响0人
微凉初夏
final class FindHelper {
static let share = FindHelper()
var currentViewCotroller: UIViewController? {
var result: UIViewController? = nil
var window: UIWindow
guard let _window = UIApplication.shared.keyWindow else {
return result
}
window = _window
if window.windowLevel != UIWindow.Level.normal {
guard let _tmpWin = UIApplication.shared.windows
.filter({ $0.windowLevel == UIWindow.Level.normal })
.first else {
return result
}
window = _tmpWin
}
var nextResponder: UIResponder? = nil
let appRootVC = window.rootViewController
// 如果是present上来的appRootVC.presentedViewController 不为nil
if let presentedVC = appRootVC?.presentedViewController {
nextResponder = presentedVC
} else {
let frontView = window.subviews[0]
nextResponder = frontView.next
}
if let tabbar = nextResponder as? UITabBarController {
if let nav = tabbar.viewControllers?[tabbar.selectedIndex] as? UINavigationController {
result = nav.children.last
}
} else if let nav = nextResponder as? UINavigationController {
result = nav.children.last
} else {
result = nextResponder as? UIViewController
}
return result
}
}