Tek Yin
Tek Yin

Reputation: 3050

How to pop a UIViewController on NavigationController and push UIView at the same time

I am facing a problem on UINavigationController...

I have this hierarchy

UINavigationController
 |- root controller
 |- ViewController A

and I have a button in ViewController A doing something and push ViewController B, but I want to remove ViewController A before adding ViewController B

So the hierarchy is going like this after the process

UINavigationController
 |- root controller
 |- ViewController B

It supposed to be sliding from ViewController A to ViewController B, but if you press back, it return to root Controller

Thank you in advance.

Upvotes: 0

Views: 2388

Answers (4)

Lefteris
Lefteris

Reputation: 14667

You should use the setViewControllers method of the UINavigationController and simply add as an array the root and viewController B

//get the existing navigationController view stack
NSMutableArray* newViewControllers = [NSMutableArray arrayWithArray:self.navigationController.viewControllers];

//drop the last viewController and replace it with the new one!
ViewControllerB *childController = [[ViewControllerB alloc] initWithNibName:@"ViewControllerB" bundle:nil];
[newViewControllers replaceObjectAtIndex:newViewControllers.count-1 withObject:self];

//set the new view Controllers in the navigationController Stack
[self.navigationController setViewControllers:newViewControllers animated:YES];

Upvotes: 3

Michael Ochs
Michael Ochs

Reputation: 2870

Have a look at [UINavigationController setViewControllers:animated:]

[self.navigationController setViewControllers:@[rootViewController, viewControllerB] animated:YES];

This should result in a push animation.

But to be honest: If you have such a UI, you most like don't want to use a NavigationController in the first place as this confuses the user. The metaphor a UINavigationController implements, is pretty straight forward. You really don't want to mess with that. You might want to have a look into the Apple Human Interface Guidelines and then choose another option of presenting your views!

Upvotes: 0

Murtuza Kabul
Murtuza Kabul

Reputation: 6514

May be this might help you.

iphone NavigationController clear views stack

It is rather a different approach to the problem. If you have the instance of required view controller available, you can always pop to it.

Upvotes: 0

AppleDelegate
AppleDelegate

Reputation: 4249

The best method would be to start the navigationController with a new ViewController instead of removing and pushing simultaneously..

on push from ViewController A,

[self.navigationController initWithRootViewController:ViewControllerB];

Upvotes: -2

Related Questions