Steve
Steve

Reputation: 6362

How to pop to an arbitrary view controller from anywhere in a navigation stack

I'm working on a navigation based app, and I chose it so that I can push and pop controllers on and off the stack. It's easy enough to move forward - just push a new controller. And moving back is easy as long as you go to the root view controller. There is a method called popToViewController:animated, but I didn't create the controller I want to pop to from within my current view controller, so the compiler complains that I haven't declared it. I know it's the second controller on the stack (one above the root). Can I use that to get there?

Upvotes: 4

Views: 2184

Answers (2)

logancautrell
logancautrell

Reputation: 8772

I generally create a NavigationController object which has knowledge about both my UINavigationController and my viewControllers. If you give each of your VCs a reference to an object like this, or make it a singleton, then it can handle things like this for you.

There is nothing wrong with embedding navigation logic in view controllers, but it can make them harder to maintain when they know about every other view controller. Encapsulating navigation logic in a shared object makes your app easier to understand and maintain.

YMMV

Upvotes: 1

Daniel
Daniel

Reputation: 22395

The viewControllers property of a UINavigationController has the viewControllers in order that they were pushed, so you can use that and your knowledge of which view controller it is to pop to that view controller..here is a reference UINavigationController ref

Upvotes: 4

Related Questions