1

I've got 4 ViewControllers attached to a NavigationController. The order of them is 1->2->3->4. When the user presses the back button on 4, I'd like them to be redirected to 2 instead of 3. At the same time, I'd also like the user to be directed back to 2 when the back button is pressed on 3. Is this possible? Thanks in advance.

qunayu
  • 1,187
  • 1
  • 11
  • 18
  • Use unwind segue, there are many similar answers. Here is [one](http://stackoverflow.com/q/24029586/5099208) – Idan Nov 30 '16 at 05:56
  • If you want swift answer then have a look at this one http://stackoverflow.com/questions/31878108/ios-swift-poptoviewcontroller-by-name – Nirav D Nov 30 '16 at 05:59
  • use unwined segue http://stackoverflow.com/questions/12561735/what-are-unwind-segues-for-and-how-do-you-use-them – Cruz Nov 30 '16 at 08:24

3 Answers3

1

Of course you can do this. Simply create the left bar button on 4th ViewController. and on that button action pop to 2nd viewcontroller

      if let viewcontroller = self.navigationController?.viewControllers[1] where viewcontroller.isKindOfClass(YourController) {
       self.navigationController?.popToViewController(viewcontroller, animated: false)          }
Sahil
  • 9,096
  • 3
  • 25
  • 29
  • Small changes in Swift3: if let viewcontroller = self.navigationController?.viewControllers[1], viewcontroller is YourViewController { let _ = self.navigationController?.popToViewController(viewcontroller, animated: false) } – Thomas G. Nov 30 '16 at 06:24
  • Thank you! It worked. Another question because I'm an absolute beginner: How do I assign this to a back button? I looked through the list of UIBarButtonSystemItems but there doesn't seem to be a back button available. – qunayu Nov 30 '16 at 23:35
  • on 4th viewcontroller viewDidload self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: image, style:.Plain, target: self, action:#selector(self.back(_:))) and action func backButtonAction(sender: AnyObject) { if let viewcontroller = self.navigationController?.viewControllers[1] where viewcontroller.isKindOfClass(YourController) { self.navigationController?.popToViewController(viewcontroller, animated: false) } } – Sahil Dec 01 '16 at 05:28
0
if let vc = self.viewControllerWithClass(YourVC.self) {

                    self.popToViewController(vc, animated: true)
}


extension UINavigationController {

    func viewControllerWithClass(_ aClass: AnyClass) -> UIViewController? {

        for vc in self.viewControllers {

            if vc.isMember(of: aClass) {

                return vc
            }
        }

        return nil
    }
}
Chirag kukreja
  • 433
  • 2
  • 5
0

You can check for the controller in navigation stack.

let controllers = navigationController!.viewControllers.reverse()
    for controller in controllers
    {
        if controller.isKindOfClass(YourController)
        {
            self.navigationController?.popToViewController(controller, animated: true)
            return
        }
    }