Search code examples
iphoneiosbuttonuinavigationbarback

Detect if back button is pressed AND wait user action to pop to previous view


I saw multiple questions about how to detect when the user is pressing the "Back" button on a UINavigationBar, but the answers does not solved my problem.

Indeed, I want to display a UIAlertView when user is pressing the UINavigationBar "Back" button, to ask him "Do you want to save the changes ?".

I can display a UIAlertView when the user is pressing the "Back" button (with the following snippet), but the previous view is popped in the same time. And I don't want this behaviour ! I just want that the app WAIT the user answer BEFORE pop the previous view...

-(void) viewWillDisappear:(BOOL)animated
{
    if ([self isMovingFromParentViewController])
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Avertissement" message:@"Voulez-vous enregistrer les modifications effectuées ?" delegate:self cancelButtonTitle:@"Retour" otherButtonTitles:@"Oui", @"Non", nil];
        [alert show];
    }
    [super viewWillDisappear:animated];
}

Thanks for you help...


Solution

  • I Suggest you using you own LeftbarButtonItem instead of default Back-button event at viewWillDisappear like this:-

    - (void)viewDidLoad
    {
      UIBarButtonItem *left=[[UIBarButtonItem alloc]initWithTitle:@"Back" style:UIBarButtonItemStyleBordered target:self action:@selector(actionBack:)];
        self.navigationItem.leftBarButtonItem = left;
     [super viewDidLoad];
    }
    
    - (IBAction)actionBack:(id)sender {
       UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Avertissement" message:@"Voulez-vous enregistrer les modifications effectuées ?" delegate:self cancelButtonTitle:@"Retour" otherButtonTitles:@"Oui", @"Non", nil];
        [alert show];
    }
    

    And use alert Delegate clickedButtonAtIndex

    - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex  
        {
            if(alertView.tag == 1)
            {
                // set your logic
            }
        }