Amit89提供了一种解决方案。您必须调用
.windowAppDelegate
的属性。因此,我从下面的链接中更改了Swift代码,使其可以正常工作以找到最顶层的ViewController。确保该视图已经在视图层次结构中。因此,无法从
.viewDidLoad
查找最顶层ViewController *的扩展
extension UIApplication { class func topViewController(base: UIViewController? = (UIApplication.sharedApplication().delegate as! AppDelegate).window?.rootViewController) -> UIViewController? { if let nav = base as? UINavigationController { return topViewController(base: nav.visibleViewController) } if let tab = base as? UITabBarController { if let selected = tab.selectedViewController { return topViewController(base: selected) } } if let presented = base?.presentedViewController { return topViewController(base: presented) } return base }}该代码源自GitHub用户Yonat,它是对ObjectiveC等效项的注释。我只更改了一些代码,以使其在没有该
.keyWindow属性的情况下也能正常工作



