Question

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?

Was it helpful?

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.

OTHER TIPS

Instead of pushing a detail view controller, the usual way to gather data is to present one modally. That will give you 2 free spaces on the left and right of the (new) navigation bar to place a Save and Cancel button.

UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:detailViewController];
[self presentViewController:navigationController animated:YES completion:nil];
// detailViewController will have to set up buttons in its init

You can use a delegate protocol you create to handle save and cancel actions in the presenting (i.e. not the detail) view controller.

Overview: The idea is to have your own barbutton to intercept the backing out from the VC.

In your viewDidLoad you can do this

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

Then your Back: method can do this

-(void)Back:(id) sender
{
    //Your code for showing AlertView with delegate as self. Remember to conform to the UIAlertViewDelegate protocol.
}

Then put your save functionality in

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (selected buttonIndex is the one for saving data)
    {
        //save your data            
    }
    //popViewController
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top