iosswiftxcodeuiviewcontrollerstoryboard

Clear/Remove multiple ViewController in NavigationController


I hope you can help me with this issue.

I am developing this iOS application with multiple ViewControllers, as shown in the following image. enter image description here

I navigate from VC1 to VC2, VC2 to VC3 until I reach VCn. When I arrive at this ViewController, I need to go to VC4. I know I could go with a segue to VC4, but the problem is that it would be stored in the navigation stack, which I want to avoid.

How can I navigate to VC4 from VCn while also clearing the navigation stack (VC2, VC3... VCn), and then return to VC1 from VC4?

I hope you can help me! 😄


Solution

  • All you need to do is to set the navigation controller's viewControllers property to an array of two elements - the root view controller (VC1), and the new VC4.

    if let navigationController {
        let vc4 = ... // initialise VC4 appropriately
        // make the array
        let newStack = [navigationController.viewControllers[0], vc4]
        // this sets viewControllers, with a "push" transition
        navigationController.setViewControllers(newStack, animated: true)
    }
    

    If you want a "pop" transition instead, first remove all the elements in viewControllers except the first and the last, then insert VC4 in between the remaining 2 VCs. Then you can popViewController(animated: true) to go to VC4.

    if let navigationController {
        let vc4 = ... 
        navigationController.viewControllers.removeSubrange(1..<navigationController.viewControllers.count - 1)
        navigationController.viewControllers.insert(vc4, at: 1)
        navigationController.popViewController(animated: true)
    }