Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIAlertViewDelegate:clickedButtonAtIndex and two buttons

guys:

There is two buttons in my viewController of test app, the right one I call it "NO",

and the other one is "YES". The two buttons will call two different functions, and when

user press one of the buttons , I want show the user an alert to confirm that.

I know use the UIAlertViewDelegate

- (void)alertView:(UIAlertView *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex

but there is two buttons, I am puzzled. How can I know which button is pressed.

So,pls help me with this, thank you in advance!

like image 631
jxdwinter Avatar asked Apr 02 '12 12:04

jxdwinter


1 Answers

When you create an UIAlertView you can set up a tag for it

-(IBAction)yesButtonClick:(id)sender{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Title" message:@"Message" delegate:self cancelButtonTitle: @"Cancel" otherButtonTitles:@"OK", nil];
    alert.tag = 101;
    [alert show];
}

-(IBAction)noButtonClick:(id)sender{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Title" message:@"Message" delegate:self cancelButtonTitle: @"Cancel" otherButtonTitles:@"OK", nil];
    alert.tag = 102;
    [alert show];
}

In the delegate method check which alert is being shown

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (alertView.tag == 101) {
        // from YES button
    }
    else if (alertView.tag == 102) {
        // from NO button
    }
}
like image 143
beryllium Avatar answered Oct 13 '22 01:10

beryllium