Multiple UIAlertView; each with their own buttons and actions

DiscoveryOV picture DiscoveryOV · Mar 4, 2012 · Viewed 22.8k times · Source

Im creating a view in Xcode 4.3 and im unsure how to specify multiple UIAlertView's that have their own buttons with separate actions. Currently, my alerts have their own buttons, but the same actions. Below is my code.

-(IBAction)altdev {
    UIAlertView *alert = [[UIAlertView alloc] 

                          initWithTitle:@"titleGoesHere"
                          message:@"messageGoesHere"
                          delegate:self
                          cancelButtonTitle:@"Cancel"
                          otherButtonTitles:@"Continue", nil];
[alert show];
}

-(IBAction)donate {
    UIAlertView *alert = [[UIAlertView alloc] 

                          initWithTitle:@"titleGoesHere"
                          message:@"messageGoesHere"
                          delegate:self
                          cancelButtonTitle:@"Cancel"
                          otherButtonTitles:@"Continue", nil];
    [alert show];
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://www.examplesite1.com"]];
         }
}


-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"examplesite2.com"]];
    }
}  

Thanks for any help!

Answer

cxa picture cxa · Mar 4, 2012

There is a useful property tag for UIView(which UIAlertView subclass from). You can set different tag for each alert view.

UPDATE:

#define TAG_DEV 1
#define TAG_DONATE 2

- (IBAction)altdev {
    UIAlertView *alert = [[UIAlertView alloc] 

                          initWithTitle:@"titleGoesHere"
                          message:@"messageGoesHere"
                          delegate:self
                          cancelButtonTitle:@"Cancel"
                          otherButtonTitles:@"Continue", nil];
   alert.tag = TAG_DEV;
   [alert show];
}

- (IBAction)donate {
    UIAlertView *alert = [[UIAlertView alloc] 

                          initWithTitle:@"titleGoesHere"
                          message:@"messageGoesHere"
                          delegate:self
                          cancelButtonTitle:@"Cancel"
                          otherButtonTitles:@"Continue", nil];
    alert.tag = TAG_DONATE;
    [alert show];
}

-(void)alertView:(UIAlertView *)alertView
clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (alertView.tag == TAG_DEV) { // handle the altdev
      ...
    } else if (alertView.tag == TAG_DONATE){ // handle the donate

    }
}