[英]Swift 4 - How to set and show a new root view controller from current view controller
在这方面挣扎了几天...
我已经在didFinishLaunchingWithOptions
从AppDelegate
设置了rootVC
,并且工作正常。
现在从rootVC
我希望,如果满足某些条件,例如。 if x=y
则设置并显示一个新的rootVC
。
我的堆栈很长一段时间都溢出了,找到了不同的解决方案,但是没有一个起作用。
下面是编译并执行的程序,我检查了断点,但应用程序中未显示任何内容。
animated Bool false
self Regional2.IrelandViewController 0x0000000102b0ff30
newViewController Regional2.IrelandMain 0x0000000102d0d300
customViewControllersArray NSArray 0x00000001c000b620
ObjectiveC.NSObject NSObject
Exception State Registers
far unsigned long 0x00000001b0a7ba78
esr unsigned int 0x92000007
exception unsigned int 0x00000000
Floating Point Registers
General Purpose Registers
和一段代码。 。 。
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let newViewController = self.storyboard?.instantiateViewController(withIdentifier: "IrelandMain") as! IrelandMain
let customViewControllersArray : NSArray = [newViewController]
self.navigationController?.viewControllers = customViewControllersArray as! [UIViewController]
self.navigationController?.pushViewController(newViewController, animated: true)
}
请注意, navigationController
show会产生相同的输出。 没有什么变化。
该代码对我有用。 它只是替换了整个UIWindow。
当我尝试只替换rootViewController时,它做到了,但是又创建了另一个(所以我在视图层次结构中加载了两个viewControllers)
if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
// If we only reloads the rootViewController than the main window has 2 subviews
// The older cannot be removed and the new can be removed.
// The workaround I found is to replace the whole UIWindow with new one
let root = UIStoryboard(name: "Main", bundle: Bundle.main).instantiateInitialViewController()
let newWindow = UIWindow()
appDelegate.replaceWindow(newWindow)
newWindow.rootViewController = root
}
并在您的AppDelegate中
func replaceWindow(_ newWindow: UIWindow) {
if let oldWindow = window {
newWindow.frame = oldWindow.frame
newWindow.windowLevel = oldWindow.windowLevel
newWindow.screen = oldWindow.screen
newWindow.isHidden = false
window = newWindow
oldWindow.removeFromSuperview()
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.