Select Page

If you just want to show a popup message without responding to the buttons pressed look at the snippet : “Popup message in iOS”

If you want to respond to a popup message the popup message probable has more than 1 button. To figure out what button got pressed we have to do a few things:

1. Add “UIAlertViewDelegate” to the header file whose implementation is going to show the popup message.

1
2
//This goes in the header (.h) file
@interface MyViewController : UIViewController <UIAlertViewDelegate>

Adding this protocol to your header file makes your code listen to the response from a popup message.

2. Show the popup message

1
2
3
4
5
6
7
8
//This goes in the implementation (.m) file
UIAlertView *message = [[UIAlertView alloc] initWithTitle:@"Alert title"  
                                                  message:@"Alert body"  
                                                 delegate:self  
                                        cancelButtonTitle:@"Button 1"  
                                        otherButtonTitles:@"Button 2", @"Button 3", nil];  
[message show];  
[message release]; //We alloc-ed, therefore we have to release.

On line 4 the delegate is set to “self”. That means the code in this implementation file is going to listen to the response from the popup message.
On line 5 and 6 there are 3 buttons configured.

3. Now the protocol is added to the header, and the delegate is set in the alertview, we have to write some code to respond to the popup message!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex{
  // The first button (or "cancel" button)
  if (buttonIndex == 0) 
  {
    NSLog(@"User pressed: %@ ", [alertView buttonTitleAtIndex:0]);
  }	
  // The second button on the alert view
  if (buttonIndex == 1) 
  {
    NSLog(@"User pressed: %@ ", [alertView buttonTitleAtIndex:1]);
  }
  // The third button on the alert view.... and so on
  if (buttonIndex == 2) 
  {
    NSLog(@"User pressed: %@ ", [alertView buttonTitleAtIndex:2]);
  }
}

Some explanation:
Why is the method that responds to the popup called “(void)alertView:…” ? Well, that is just how it is agreed upon in the specs of the “UIAlertViewDelegate” protocol. You can read up on the protocol on the Apple docs about UIAlertViewDelegate

With this code the popup message should look like:
Popup with 3 buttons

And when you push a button there should be a line written in your XCode console that tells you which button was pressed:
Console message