How to set action to the backButtonItem on the navigation bar? I have a navigation bar, when I'm pressing the back button, I need to alert some message to the user, and only after user's reaction - return to the previous view. How can I do it? Thanx!
- (void)viewDidLoad
{
[super viewDidLoad];
//no one field don't changed yet
isDirty = FALSE;
//edited user
//set default values
newData = [data copy];
//setting navigation controller rigth button
UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithTitle:@"Save"
style:UIBarButtonSystemItemDone
target: self
action: @selector(saveBtnUserClick)];
self.navigationItem.rightBarButtonItem = rightButton;
[rightButton release];
UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:@"Back"
style:UIBarButtonSystemItemDone
target: self
action: @selector(backBtnUserClick)];
self.navigationItem.backBarButtonItem = leftButton;
[leftButton release];
}
//and my method for reaction
-(IBAction) backBtnUserClick
{
NSLog(@"\n Back pressed");
//back to previous view
[self.navigationController popViewControllerAnimated: TRUE];
}
This sounds like a job for UIAlertView
. Instead of calling popViewControllerAnimated: in your IBAction
methods, alloc/init a UIAlertView
and present it. Then, when the user taps a button on the UIAlertView
, dismiss the UIAlertView
and call popViewControllerAnimated:
.
- (IBAction)backBtnUserClicked:(id)object {
UIAlertView *av = [[[UIAlertView alloc] initWithMessage:@"Wait!"
delegate:self
cancelButtonTitle:@"Ok"
otherButtonTitles:nil] autorelease];
[av show];
}
In your UIAlertViewDelegate
methods call popViewControllerAnimated:
.
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
[[self navigationController] popViewControllerAnimated:YES];
}
To set the action on the back button:
[[[self navigationController] leftBarButtonItem] setTarget:self];
[[[self navigationController] leftBarButtonItem] setAction:@selector(backBtnUserClicked:)];