Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iPhone: How do I override the back button in a Navigation Controller?

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!!

like image 729
Angelo Stracquatanio Avatar asked Jan 07 '11 20:01

Angelo Stracquatanio


People also ask

How do I get rid of the back button on my navigation bar?

Touch “Settings” -> “Display” -> “Navigation bar” -> “Buttons” -> “Button layout”. Choose the pattern in “Hide navigation bar” -> When the app opens, the navigation bar will be automatically hidden and you can swipe up from the bottom corner of the screen to show it.

How do I get rid of the back button on my Iphone?

Yes, the back button can be disabled. Please navigate to Advanced Website Kiosk Settings–>Navigation–>Disable back button. Kindly enable this restriction to disallow the usage of the back button on the iOS device.


2 Answers

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.

like image 149
Amy Worrall Avatar answered Nov 14 '22 22:11

Amy Worrall


Simple solution:

- (void)viewWillDisappear:(BOOL)animated {  
    //if true, back was pressed 
    if ([self.navigationController.viewControllers indexOfObject:self]==NSNotFound) {
             //your logic
    }   
}
like image 23
Luda Avatar answered Nov 14 '22 23:11

Luda