如果没有UINavigationController,我似乎无法得到最顶端的UIViewController。以下是我目前所掌握的:
UIApplication.sharedApplication().keyWindow?.rootViewController?.presentViewController(vc, animated: true, completion: nil)
然而,它似乎没有做任何事情。keyWindow和rootViewController似乎也不是nil值,所以可选的链接应该不是问题。
注意:这样做不是一个好主意。它打破了MVC模式。
对于swift 4 / 5 +获取topmost viewController
// MARK: UIApplication extensions
extension UIApplication {
class func getTopViewController(base: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
if let nav = base as? UINavigationController {
return getTopViewController(base: nav.visibleViewController)
} else if let tab = base as? UITabBarController, let selected = tab.selectedViewController {
return getTopViewController(base: selected)
} else if let presented = base?.presentedViewController {
return getTopViewController(base: presented)
}
return base
}
}
如何使用
if let topVC = UIApplication.getTopViewController() {
topVC.view.addSubview(forgotPwdView)
}