Go back multiple ViewControllers from NavigationController back button

1.9k views Asked by At

I want to go back two ViewControllers rather than one when I click the back button on the NavigationController.

  override func viewWillDisappear(_ animated: Bool)
    {
        super.viewWillDisappear(animated)

        if self.isMovingFromParent
        {
            let vc = self.navigationController?.viewControllers[1] as! MyViewController

            self.navigationController?.popToViewController(vc, animated: false)
        }
    }

This works almost the way that I want it to. Changing self.navigationController?.viewControllers[1] lets me go to any ViewController in the stack. The only issue I have is that it always briefly displays the top most viewController briefly before going directly to the ViewController that I have popped to. How do I stop it from displaying the intermediate ViewController?

My problem is:

VC[0] → VC[1] → VC[2] → VC[3]

From 3 I want to go back to 1 directly without it having to display 2. I want to do this from the NavigationController back button.

2

There are 2 answers

1
Yogesh Tandel On

If you have a viewController in stack you can go back to it by using the class name.

let viewControllers: [UIViewController] = self.navigationController!.viewControllers ;
for aViewController in viewControllers {
    if(aViewController is HomeViewController){
       self.navigationController!.popToViewController(aViewController, animated: true);
    }
}
2
Christian Ray Leovido On

You can use unwind segues for this

Try putting this code in the UIViewController that you want to go back to

@IBAction func unwindHere(segue:UIStoryboardSegue) {}

Go to the Storyboard and look for the viewController that you want to go back from (VC3 in your case), and CTRL + DRAG the view controller icon to the exit icon. This will show unwindHere

Select the unwindHere unwind segue in the left panel of your VC3 to give it an identifier name, e.g. unwindSegueToVC1

Create a function that will perform the segue with the identifier name to unwind to the view controller that you want (VC1)

override func viewDidLoad() {
    super.viewDidLoad()

    setupNavigationBar()

}

@objc func unwindToFirstViewController() {     
     performSegue(withIdentifier: "unwindSegueToVC1", sender: self)
}

func setupNavigationBar() {

    self.navigationController?.navigationItem.leftBarButtonItem?.action = #selector(unwindToFirstViewController)

}