Detecting button click with UIAlertView Detecting button click with UIAlertView xcode xcode

Detecting button click with UIAlertView


To detect the button clicks the alert view must have an associated delegate, e.g.

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"add button pressed"                                                message:@"Add to record"                                               delegate:self    // <------                                      cancelButtonTitle:@"Cancel"                                      otherButtonTitles:@"OK", nil];


This is your code which i used and added some my code also.**

-(IBAction) Add {          UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"add button pressed"                                                       message:@"Add to record"                                                      delegate:nil                                                  cancelButtonTitle:@"Cancel"                                              otherButtonTitles:@"OK", nil];       alert.tag=101;//add tag to alert       [alert show];       [alert release];     }

Now when you press button on alert it will call clickedButtonAtIndex but there should a identifier for every alert. So add tag and then

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex** {//  the user clicked one of the OK/Cancel buttonsif(alertView.tag == 101)     // check alert by tag {    if (buttonIndex == 0)   {    //just to show its working, i call another alert view    UIAlertView *alert = [[UIAlertView alloc] initWithTitle: @"OK WORKIng well"                                                    message:@"no error"                                                   delegate:nil                                          cancelButtonTitle:@"IWORKS"                                           otherButtonTitles:@"NO PRB", nil];    [alert show];    [alert release];    }else{    NSLog(@"cancel");       }}}

Hope it helps.


The buttonIndex of 0 is the cancel button. I would recommend using:

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {if (buttonIndex == 0){      NSLog(@"cancel");   }else{   UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"OK works" message:@"no error" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];                                                                                                                  [alert show];    [alert release];        }}