0

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.

Joshua
  • 3,055
  • 3
  • 22
  • 37
Punreach Rany
  • 2,560
  • 7
  • 23
  • 56
  • 1
    Use `viewControllers` property of the navigation controller to find which one you want to pop to, and then call `popToViewController(_:animated:)` to pop to it. – Larme Oct 20 '21 at 08:39
  • Could you show me a sample code? – Punreach Rany Oct 20 '21 at 08:40
  • How do you know which view controller you want to pop to? What's the logic behind it? – Larme Oct 20 '21 at 08:40
  • Say I did this. One -> Two -> Three -> Four -> Five. And I want to pop from Five until Two. How do I do that? – Punreach Rany Oct 20 '21 at 08:55
  • `guard let navigationController = navigationController else { return }; let targetVC = navigationController.viewControllers[1]; navigationController.popToViewController:(targetVC, animated: true)` ? It's pretty straightforward, I don't see the issue. – Larme Oct 20 '21 at 08:59
  • https://stackoverflow.com/questions/38339737/swift-how-to-popviewcontrolleranimated-two-views-back/38341017 or if it's by class: https://stackoverflow.com/questions/26343546/how-to-pop-view-controller-to-one-of-the-previous-view-controllers-in-swift – Larme Oct 20 '21 at 09:01
  • Does this answer your question? [Swift - How to popViewControllerAnimated two views back](https://stackoverflow.com/questions/38339737/swift-how-to-popviewcontrolleranimated-two-views-back) – Larme Oct 20 '21 at 09:43

1 Answers1

3

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)
        }
    }
}
son
  • 1,058
  • 6
  • 7