如果无法UIViewController访问UINavigationController. 这是我到目前为止所拥有的:
UIViewController
UINavigationController
UIApplication.sharedApplication().keyWindow?.rootViewController?.presentViewController(vc, animated: true, completion: nil)
但是,它似乎没有做任何事情。和似乎keyWindow也是rootViewController非零值,因此可选链接不应该成为问题。
keyWindow
rootViewController
注意: 做这样的事情是个坏主意。 它打破了 MVC 模式。
presentViewController显示一个视图控制器。它不返回视图控制器。如果您不使用 a UINavigationController,您可能正在寻找presentedViewController并且您需要从根开始并向下遍历呈现的视图。
presentViewController
presentedViewController
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 }