Search code examples
iosios7uinavigationitem

How do I override the back navigationItem?


In my RecordViewController, within the didSelectRowAtIndexPath I push a detailViewController (which inherits from UIViewController):

[[self navigationController] pushViewController:detailViewController animated:YES];

Once the DetailViewController appears I can see a Back navigationButton in the top left corner, which automatically pops the current view controller to get back to the previous ViewController.

Now I need to show a UIAlertView and ask the user, if the data should be saved or not.

And only when the user has made a decision, the current view controller should disappear.

My problem is if I put this code into viewWillDisappear, it is already too late. I can't stop the process while showing the UIAlertView. This needs to be intercepted the moment the user pressed the back button.

Is there a method I could override to achieve this?


Solution

  • Create a UIBarButtonItem:

    UIBarButtonItem * backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle: @"Back"
        style: UIBarButtonItemStyleDone target: self action: @selector(onBackButtonTapped:)];
    

    Assign it to left bar button item:

    self.navigationItem.leftBarButtonItem = backBarButtonItem;
    

    Implement onBackButtonTapped API:

    - (void) onBackButtonTapped: (id) sender
    {
        // Display an UIAlertView
    }
    

    You may want to customize the back button. Please look into UIBarButtonItem for more details.