如果没有UINavigationController,我似乎无法得到最顶端的UIViewController。以下是我目前所掌握的:
UIApplication.sharedApplication().keyWindow?.rootViewController?.presentViewController(vc, animated: true, completion: nil)
然而,它似乎没有做任何事情。keyWindow和rootViewController似乎也不是nil值,所以可选的链接应该不是问题。
注意:这样做不是一个好主意。它打破了MVC模式。
presentViewController显示一个视图控制器。它不会返回一个视图控制器。如果你不使用UINavigationController,你可能正在寻找presenttedviewcontroller,你需要从根开始,向下迭代所呈现的视图。
if var topController = UIApplication.sharedApplication().keyWindow?.rootViewController {
while let presentedViewController = topController.presentedViewController {
topController = presentedViewController
}
// topController should now be your topmost view controller
}
对于Swift 3+:
if var topController = UIApplication.shared.keyWindow?.rootViewController {
while let presentedViewController = topController.presentedViewController {
topController = presentedViewController
}
// topController should now be your topmost view controller
}
适用于iOS 13+
let keyWindow = UIApplication.shared.windows.filter {$0.isKeyWindow}.first
if var topController = keyWindow?.rootViewController {
while let presentedViewController = topController.presentedViewController {
topController = presentedViewController
}
// topController should now be your topmost view controller
}