Search code examples
iosobjective-cuinavigationcontrolleruinavigationitem

Prevent leftBarButtonItem navigationItem show alert


I have a text editing view, and I would like to prompt the user before returning to the rootview when the text has been edited.

I have tried this so far.

self.navigationItem.leftBarButtonItem.title = @"Back";
self.navigationItem.leftBarButtonItem.tintColor = [UIColor grayColor];


-(void) viewWillDisappear:(BOOL)animated {
    if ([self.navigationController.viewControllers indexOfObject:self]==NSNotFound) {
        // back button was pressed.  We know this is true because self is no longer
        // in the navigation stack.
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Confirm Submission" message:@"Current Job Sheet Incomplete\n Please Confirm Your Submission" delegate:self cancelButtonTitle:@"Submit" otherButtonTitles:@"Cancel", nil];
        alert.tag = 1;
        [alert show];
    }
//    [super viewWillDisappear:animated];
}

Although this shows the alert, it dose not stop the user from being pushed to the root view.


Solution

  • Add a custom button on leftBarButton

    UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle:@"Back" style: UIBarButtonItemStylePlain target:self action:@selector(navigationBackBtnTap)];
    self.navigationItem.leftBarButtonItem = backButton;
    
    -(void)navigationBackBtnTap{
             UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Confirm Submission" message:@"Current Job Sheet Incomplete\n Please Confirm Your Submission" delegate:self cancelButtonTitle:@"Submit" otherButtonTitles:@"Cancel", nil];
             alert.tag = 1;
             [alert show];
    }