使用Side菜单更改根视图控制器

时间:2017-05-13 02:24:14

标签: ios swift side-menu

我试图用另一个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")
})

}

Picture before change RootviewController When I clicked that gray button then changeRootView function will run.

Then changeRootView function changed App keyWindow's rootViewController

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

1 个答案:

答案 0 :(得分: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")
                }
    )
}

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