Swift 4 - 如何从当前视图控制器设置和显示新的根视图控制器

时间:2017-12-05 18:35:18

标签: ios swift viewcontroller

用这个挣扎了几天......

我在rootVC的{​​{1}}设置了AppDelegate,这很正常。

现在从那个didFinishLaunchingWithOptions我想要的,如果满足某些条件,例如。 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) show会产生相同的输出。什么都没有改变。

1 个答案:

答案 0 :(得分:0)

该代码适合我。 它只是取代了整个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()
    }
}