Swift ios set a new root view controller

前端 未结 20 870
醉话见心
醉话见心 2020-12-13 04:46

I wonder if its possible to set a new root VC?

My app gets init with a uinavigation controller that has a table view to be the root VC.

Then from the table v

20条回答
  •  北海茫月
    2020-12-13 04:57

    Link to a related question

    This answer applies to usage of an existing ViewController from somewhere in the current stack without instantiating and reconfiguring a new controller.

    The documentation says: The root view controller provides the content view of the window. Assigning a view controller to this property (either programmatically or using Interface Builder) installs the view controller’s view as the content view of the window. The new content view is configured to track the window size, changing as the window size changes. If the window has an existing view hierarchy, the old views are removed before the new ones are installed.

    Just as the documentation says: It removes all views in the stack if the rootViewController is exchanged. No matter what's with the controller. So remove the ViewController from the stack to assure its view won't be removed.

    This resulted in my case in the following solution:

        if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
            guard let pageVC = self.onboardingDelegate as? OnboardingPageViewController else { return } // my current stack is in a pageViewController, it also is my delegate
            let vc = self // holding myself
            pageVC.subViewControllers.removeLast() // removing myself from the list
            pageVC.setViewControllers([pageVC.subViewControllers[0]], direction: .forward, animated: false, completion: nil) // remove the current presented VC
            appDelegate.window?.rootViewController = vc
            vc.onboardingDelegate = nil
            appDelegate.window?.makeKeyAndVisible()
        }
    

提交回复
热议问题