What are the button indexes in a three-button UIAlertView

iOS Simulator Screen shot 30 Dec 2013 09.50.43

The cancel button is always index 0, and all other buttons in the array start at index 1 counting up.

For completion, here’s how to create it:

- (IBAction)showAlert:(id)sender {
    // create an alert view with three buttons
    UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"Three Button Alert" message:@"This is an alert view with more than two buttons. Will it work?" delegate:self cancelButtonTitle:@"No Way (0)" otherButtonTitles:@"Perhaps (1)", @"Definitely! (2)", nil];
    [alertView show];

And here’s how to react to it:

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    switch (buttonIndex) {
        case 0:
            NSLog(@"That was button at index 0");
            case 1:
            NSLog(@"That was button at index 1");
            case 2:
            NSLog(@"That was button at index 2");
            case 3:
            NSLog(@"We don't have a fourth button");

This is a delegate method, so the reacting class needs to conform to the UIAlertView Protocol like so:

@interface ViewController : UIViewController <UIAlertViewDelegate>

Jay is founder of WP Hosting, a boutique style managed WordPress hosting and support service. He has been working with Plesk since version 9 and is a qualified Parallels Automation Professional. In his spare time he likes to develop iOS apps and WordPress plugins, or drawing on tablet devices. He blogs about his coding journey at http://wpguru.co.uk and http://pinkstone.co.uk.

You can leave a comment on my original post.