neo
neo

Reputation: 1404

How to pop all view controllers except one?

Let I have FirstViewController. From FirstViewController, user opens modally UINavigationController(rootViewController: SecondViewController()). From SecondViewController, user can go further and further using pushViewController method. During this travel, user comes to FifthViewController, where close button exists as a leftBarButtonItem. When it is pressed, I want to show FirstViewController, not SecondViewController. How to achieve this using best practice?

My idea: From FifthViewController, it is possible to use popToRootViewController method. It will show SecondViewController. In SecondViewController, I need to somehow handle this (I don't know how) and dismiss it. But I don't think that this method is correct. Also, this method is long, because SecondViewController is shown (that can be possibly avoided). So, what is the best way?

Upvotes: 0

Views: 52

Answers (2)

kerry
kerry

Reputation: 2582

All you need to do is call self.dismiss on any of the children of navigation controller. This will remove all of your pushed view controllers in UINavigationController and dismiss the UINavigationController itself.

Upvotes: 1

Stefan Wieland
Stefan Wieland

Reputation: 253

You can find the navigation stack in navigationController?.viewControllers. Take the viewController you are looking for and use

navigationController?.popToViewController(someViewController, animated: true)

to go back.

Upvotes: 0

Related Questions