Search code examples
swiftuiviewcontrollerseguedismiss

How can I go back to ViewController2 from ViewController5 - Swift


In swift I have ViewController1, ViewController2, ViewController3, ViewController4 and ViewController5, now from ViewController1,

I go to ViewController5 by using performSegue(withIdentifier: "segueIdentifier", sender: nil) like this:

ViewController1 -> ViewController2 -> ViewController3 -> ViewController4 -> ViewController5

now I'm on the ViewController5 and I want to dismiss to the ViewController2, I use the dismiss(animated: true) and it only get you back 1 step from your current ViewController, so I get on ViewController4.

The question is, how can I go back to ViewController2 from ViewController5?

So when I got back in ViewController2 and run dismiss(animated: true) I'm going back to ViewController1


Solution

  • extension UINavigationController {
    
    func popToViewController<Controller : UIViewController>(_ type: Controller.Type){
        guard let vc = viewControllers.compactMap({ $0 as? Controller }).first else { return }
        popToViewController(vc, animated: true)
      } 
    
    }
    
    navigationController?.popToViewController(ViewController.self)