6
votes

In my app I have a basic Navigation Controller. For all of my views, except one, the controller works as it should.

However, for one view in particular, I would like the 'back' button to not go back to the previous view, but to go to one I set. In particular it is going to go back 2 views and skip over one.

After doing some research I found that I can intercept the view when it disappears, so I tried to put in code to have it navigate to the page I would like:

- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
//i set a flag to know that the back button was pressed
if (viewPushed) {
    viewPushed = NO;   
} else {
    // Here, you know that back button was pressed
    mainMenu *mainViewController = [[mainMenu alloc] initWithNibName:@"mainMenu" bundle:nil];
    [self.navigationController pushViewController:mainViewController animated:YES];
    [mainViewController release];
}   

}

That didn't work, so does anyone have any ideas?

Thanks!!

4

4 Answers

13
votes

In your code, you seem to be trying to push another view controller onto the stack, rather than pop an extra item off it.

Try this as your code that does the going back two levels:

NSArray *vcs = [self.navigationController viewControllers];
[self.navigationController popToViewController:[vcs objectAtIndex:[vcs count]-3];

Alternatively you could totally replace the back button with a button of your own? In your viewController:

UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStyleBordered target:self action:@selector(doSomething:)];

self.navigationItem.hidesBackButton = YES;
self.navigationItem.leftBarButtonItem = item;
[item release];

Then you can write the doSomething: method to pop the two items off the stack, perhaps using the code I posted above.

4
votes

Simple solution:

- (void)viewWillDisappear:(BOOL)animated {  
    //if true, back was pressed 
    if ([self.navigationController.viewControllers indexOfObject:self]==NSNotFound) {
             //your logic
    }   
}
2
votes

You can try implementing the UINavigationBarDelegate delegate. When the method -navigationBar:didPopItem: is called, you can pop an additional item from the UINavigationController, and thus pop two items at once.

-1
votes
 UIButton *home = [UIButton buttonWithType:UIButtonTypeCustom];  
UIImage *homeImage = [UIImage imageNamed:@"back.png"];  
[home setBackgroundImage:homeImage forState:UIControlStateNormal];  
[home addTarget:self action:@selector(LogOut)  
forControlEvents:UIControlEventTouchUpInside];  
home.frame = CGRectMake(0, 0, 69, 26);  
UIBarButtonItem *button2 = [[UIBarButtonItem alloc] initWithCustomView:home];
[[self navigationItem] setLeftBarButtonItem:button2];
[button2 release];
button2 = nil;