2

I'm fairly new to iOS development and I'm building an application that consists of a UINavigationController and three ViewControllers that I'll refer to as A, B and C.

View controller A is shown initially. From there, I have two workflows:

  1. A > C

  2. A > B > C

In the second workflow, I have defined shouldPerformSegue(withIdentifier) on view controller B. Inside of this method, I need to do some work to decide if I should show view controller C or cancel the segue and display an error message. Assuming that no errors occurred, the segue to view controller C will be performed. When view controller C is displayed, the back button points back to view controller B but I need it to point back to view controller A instead.

I've tried removing view controller B from the navigation stack by calling the following at the end of shouldPerformSegue(withIdentifier) just before returning true to allow the segue to proceed:

self.navigationController?.viewControllers.remove(at: index)

If I read the documentation properly, the index of the view controller to remove corresponds to the following:

The root view controller is at index 0
The back view controller is at index n-2
The top view controller is at index n-1

Unfortunately, I haven't had any luck getting this to work properly. I'm sure that I'm doing something wrong but I'm not sure what else to try. Can anyone point me in the right direction? Thank you!

bmt22033
  • 6,880
  • 14
  • 69
  • 98
  • Check out this post http://stackoverflow.com/questions/10822857/is-it-possible-to-pop-the-uinavigationcontroller-twice . – Adamsor Dec 05 '16 at 13:34
  • This is pretty common problem people encounter, but to the best of my (limited) knowledge, there's is no simple way to modify what the built in back button does. You might consider subclassing UINavigationController and overwriting it's pop method to check if the top view controller is C. If it is C, pop once with an animation and then once more with no animation. Otherwise just pop once. – Erik Dec 05 '16 at 13:37
  • 1
    `self.navigationController.popToRoot()` will solve your problem – Hossam Ghareeb Dec 05 '16 at 14:01

2 Answers2

8

you can use this:

var viewControllers = navigationController?.viewControllers

viewControllers?.removeLast(2) //here 2 views to pop index numbers of views

navigationController?.setViewControllers(viewControllers!, animated: true)

you can remove like this also..

Ahmad F
  • 30,560
  • 17
  • 97
  • 143
Sagar Snehi
  • 398
  • 3
  • 13
1

You can create custom back button and on its touchUpInside event, you can pop to specific view controller.

To pop to specific view controller , you can use this code:

your_navigationController?.popToViewController(YourViewControllerObject, animated: true)
Vishal Sonawane
  • 2,637
  • 2
  • 16
  • 21