How to react to multiple UIAlertViews

If your class creates more than one UIAlertView, then you need a way to react to each of those accordingly. Problem is, you may only have one delegate that listens to all alerts at any given time.

You could of course create a separate class for each alert view, but that’s a bit overkill. Instead, the UIView’s tag property comes in handy with which you can identify a view at runtime (and UIAlertView inherits from UIView).

tag is an integer so you can only give it whole numbers, like so:

- (void)alertOne {
    UIAlertView *infoMessage;
    infoMessage = [[UIAlertView alloc]
                   initWithTitle:@"Title 1" message:@"Message 1 goes here."
                   delegate:self cancelButtonTitle:@"Exciting stuff!" otherButtonTitles:@"Nice!", nil];
    infoMessage.alertViewStyle = UIAlertViewStyleDefault;
    infoMessage.tag = 1;
    [infoMessage show];
}

- (void)alertTwo {
    UIAlertView *infoMessage;
    infoMessage = [[UIAlertView alloc]
                   initWithTitle:@"Title 2" message:@"Message 2 goes here."
                   delegate:self cancelButtonTitle:@"Exciting stuff!" otherButtonTitles:@"Nice!", nil];
    infoMessage.alertViewStyle = UIAlertViewStyleDefault;
    infoMessage.tag = 2;
    [infoMessage show];
}

In your delegate method you can now ask which tag is set when those buttons are pressed:

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    // reacting to tag 1
    if (alertView.tag == 1) {
        if (buttonIndex == 0) {
            NSLog(@"User pressed first button");
        } else if (buttonIndex == 1) {
            NSLog(@"User pressed second button");
        }
    }
    
    // reacting to tag 2
    if (alertView.tag == 2) {
        if (buttonIndex == 0) {
            NSLog(@"User pressed first button");
        } else if (buttonIndex == 1) {
            NSLog(@"User pressed second button");
        }
    }
}

See also:





Leave a Reply