Search code examples
iosswiftuiviewcontrollernavigationstoryboard

Swift & Navigation : How do I pop until a certain ViewController?


In order to pop to Root ViewController, I can just use the following code.

navigationController?.popToRootViewController(animated: false)

But what if I want to pop until a certain View Controller in the Navigation stack, how can I do that? Please help me. Thank you.


Solution

  • The navigation controller holds a group of view controller and you can pop to any sub-controller you want. For example your flow seem like:

    HomeViewController -> ContactViewController -> ContactDetailsViewController -> ChatViewController

    Then from ChatViewController you want to push back to ContactViewController:

    class ChatViewController: UIViewController {
        ....
        func popToContact() {
            if let contactVC = self.navigationController?.viewControllers.filter { $0 is ContactViewController }.first {
                self.navigationController?.popToViewController(contactVC, animated: true)
            }
        }
    }