Brett Brett - 3 months ago 14
Objective-C Question

Replace a UIViewController in the UINavigationController hierarchy

I have an iPhone app which uses a standard implementation of

UINavigationController
for the app navigation.

I am trying to figure out a way to replace a view controller in the hierarchy.
In other words, my app loads into a
rootViewController
and when the user presses a button, the app pushes to
firstViewController
. Then the user pushes another button to navigate the app to
secondViewController
. Again the use navigates down to another view controller, thirdViewController. However, I want the BackButton of the
thirdViewController
to pop back to firstViewController.

Essentially, when the user pushes to
thirdViewController
, I would like it to replace
secondViewController
in the navigation hierarchy.


Is this possible? I know it is using Three20, but I'm not in this case. Nevertheless, if it's possible in Three20, then it certainly should be using straight SDK calls. Does anyone have any thoughts?

Cheers,
Brett

Answer

Pretty Simple, when about to push the thirdViewController inseat of doing a simple pushViewController do this:

NSArray * viewControllers = [self.navigationController viewControllers];
NSArray * newViewControllers = [NSArray arrayWithObjects:[viewControllers objectAtIndex:0], [viewControllers objectAtIndex:1], thirdController,nil];
[self.navigationController setViewControllers:newViewControllers];

where [viewControllers objectAtIndex:0] and [viewControllers objectAtIndex:1] are your rootViewController and your FirstViewController.