我正在使用此类代码替换UIApplication窗口rootViewController
extension UIWindow {
func set(rootViewController newViewController: UIViewController, withTransition transition: CATransition? = nil) {
let previousViewController = self.rootViewController
if let transition = transition {
// Add the transition
layer.add(transition, forKey: kCATransition)
}
self.rootViewController = newViewController
// Update status bar appearance using the new view controllers appearance - animate if needed
if UIView.areAnimationsEnabled {
UIView.animate(withDuration: CATransaction.animationDuration()) {
newViewController.setNeedsStatusBarAppearanceUpdate()
}
} else {
newViewController.setNeedsStatusBarAppearanceUpdate()
}
/// The presenting view controllers view doesn't get removed from the window as its currently transistioning and presenting a view controller
if let transitionViewClass = NSClassFromString("UITransitionView") {
for subview in self.subviews where subview.isKind(of: transitionViewClass) {
subview.removeFromSuperview()
}
}
if let previousViewController = previousViewController {
// Allow the view controller to be deallocated
previousViewController.dismiss(animated: false) {
// Remove the root view in case its still showing
previousViewController.view.removeFromSuperview()
}
}
}
}
几乎可以很好地工作,这是因为设置rootViewController不会在View Hierarchy Debugger中使ViewController重复。
但是它有一个警告,因为替换View Controller并没有关联self.view.window。没有基础窗口会导致例如view.convert(point,to:nil)不能正常工作,因为没有此窗口:/
任何帮助,为什么ViewController会丢失与窗口的关联