Manni Manni - 11 months ago 87
iOS Question

UINavigationController: How to cancel the back button event?

In my

I have a
with a default back button. When the user clicks the back button, a warning message should appear: "Do you really want to go back?". I know, that it is not possible to trap the back button event. It's only possible the use
and set a flag:

- (void)viewWillDisappear:(BOOL)animated {
if (backBtnPressed) {
UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:@"Question" message:@"Do you really want to go back?" delegate:self cancelButtonTitle:@"No" otherButtonTitles: @"Yes", nil] autorelease];
[alert show];

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
if (buttonIndex == 0) {
// don't go back!
// cancel the back button event
else if (buttonIndex == 1) {
// go back

But with this code I have no chance! I can't stop the back button event, isn't it?

Do I have to write my own back button and set it as
? Or is there anybody with a great idea? :-)

Thanks for your help!

Answer Source

viewWillDisappear is a delegate method for the event that the view is going to disappear - and there's nothing the developer can do about that! If you could, it would be a viewShouldDisappear delegate method.

So I guess the only way is as you suggest, to use a custom leftBarButtonItem.