我正在尝试在最上层的视图控制器(topMostViewController)中展示一个视图控制器(viewcontroller). 这个方法在iOS 12及以下版本是有效的。但是在iOS 13上,我遇到了以下错误:
手动将rootViewController的视图添加到视图层级结构中已不再受支持。请允许UIWindow自行将rootViewController的视图添加到视图层级结构中。
我已经在iOS 12及以下版本上测试了以下代码,并且它可以正常工作。但是,在iOS 13上我无法展示这个视图控制器。我在viewDidLoad
打印了一下输出,它已经被打印出来了,但是视图并没有出现。
func presentInWindow(animated flag: Bool = true, completion: (() -> Void)? = nil) {
DispatchQueue.main.async {
var alertWindow: UIWindow?
alertWindow = UIWindow(frame: UIScreen.main.bounds)
alertWindow?.windowLevel = UIWindow.Level.alert + 1
alertWindow?.rootViewController = UIApplication.topViewController()
if let rootViewController = alertWindow?.rootViewController {
alertWindow?.makeKeyAndVisible()
rootViewController.present(self, animated: flag, completion: completion)
}
}
}
static func topViewController() -> UIViewController? {
var topViewController: UIViewController?
if #available(iOS 13.0, *) {
topViewController = shared.connectedScenes
.filter({$0.activationState == .foregroundActive})
.map({$0 as? UIWindowScene})
.compactMap({$0})
.first?.windows
.filter({$0.isKeyWindow}).first?.rootViewController
} else {
topViewController = shared.delegate?.window??.rootViewController
}
while true {
if let presented = topViewController?.presentedViewController {
topViewController = presented
} else if let nav = topViewController as? UINavigationController {
topViewController = nav.visibleViewController
} else {
break
}
}
return topViewController
}