0

我正在尝试用另一个 ViewController 更改 RootViewController。但我无法弄清楚。我面临一些问题

通过上述代码更改 rootViewController 后,新的 viewController 消失。在控制台日志中:不鼓励在分离的视图控制器上显示视图控制器。请帮我!

我的代码是:

func changeRootView(){
guard let delegate = UIApplication.shared.delegate else {
    return
}
guard let window = (delegate as! AppDelegate).window else {
    return
}
UIView.transition(with: window, duration: 0.3, options: .transitionCrossDissolve, animations: {
    let lgv = DriverMainViewController()
    window.rootViewController = UINavigationViewController(rootViewController: lgv)
}, completion: { completed in
    SideMenuManager.menuLeftNavigationController!.dismiss(animated: true, completion: nil)
    print ("changed")
})

}

更改 RootviewController 之前的图片 当我单击那个灰色按钮时,changeRootView 函数将运行。

然后changeRootView函数改变了App keyWindow的rootViewController

但是这个蓝色背景的 viewController 在 1 秒内消失了。此屏幕截图是在新的根视图控制器消失后。

4

1 回答 1

1

我认为这里发生的事情是,当您设置rootViewController窗口时,rootViewController不再引用旧的并且它被 ARC 删除。您可能会尝试捕获传出的视图控制器,以便它在动画期间一直存在。尝试这个:

func changeRootView(){
    guard let delegate = UIApplication.shared.delegate else { return }
    guard let window = (delegate as! AppDelegate).window else { return }

    // capture a reference to the old root controller so it doesn't
    // go away until the animation completes
    let oldRootController = window.rootViewController

    UIView.transition(with: window, 
                  duration: 0.3, 
                   options: .transitionCrossDissolve, 
                animations: {
                    let lgv = DriverMainViewController()
                    window.rootViewController = UINavigationViewController(rootViewController: lgv)
                }, 
                completion: { completed in

                    // OK, we're done with the old root controller now
                    oldRootController = nil

                    SideMenuManager.menuLeftNavigationController!.dismiss(animated: true, completion: nil)
                    print ("changed")
                }
    )
}

这段代码所做的是添加对窗口现有根视图控制器的引用,然后在完成块中捕获它以控制它存在的时间。

于 2017-05-13T09:05:19.787 回答