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

Time:10-21

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.

CodePudding user response:

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)
        }
    }
}
  • Related