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.

3

3 Answers 3

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)          }
Sign up to request clarification or add additional context in comments.

3 Comments

Small changes in Swift3: if let viewcontroller = self.navigationController?.viewControllers[1], viewcontroller is YourViewController { let _ = self.navigationController?.popToViewController(viewcontroller, animated: false) }
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.
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) } }
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
    }
}

Comments

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
        }
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.