2

I have a button in a menu which when touched, pops up a alert message with two buttons: "Cancel" and "Yes". This is the code I have for the alert:

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Exit game"
                                                message:@"Are you sure?"
                                               delegate:nil
                                      cancelButtonTitle:@"Cancel"
                                      otherButtonTitles:@"Yes", nil];
[alert show];

Is it possible to add an action to the button "Yes"?

Newd
  • 2,174
  • 2
  • 17
  • 31
Stumpp
  • 279
  • 4
  • 7
  • 16

3 Answers3

11

In your code set the UIAlertView delegate:

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Exit game" message:@"Are you sure?" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Yes", nil]; [alert show];

As you have set delegate to self, write the delegate function in the same class as shown below:

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
if (buttonIndex == 1) { // Set buttonIndex == 0 to handel "Ok"/"Yes" button response
    // Cancel button response
    }}
Saurabh Shukla
  • 1,368
  • 3
  • 14
  • 26
1

You need to implement the UIAlertViewDelegate

and add the following...

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) {
        // do stuff
    }
}
Jason Pawlak
  • 792
  • 1
  • 6
  • 20
0

Yes it is easy. See that argument called "delegate" that you have set to nil right now? Set that to an object... usually "self" if you are calling it from your view controller and then implement the selector for UIAlertViewDelegate.

You also need to declare that your view controller conforms to the UIAlertViewDelegate protocol. A good place to do this is in the "private" continuation class of the view controller.

@interface MyViewController() <UIAlertViewDelegate>
@end

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
   NSLog(@"Button pushed: %d", buttonIndex);
}
Ray Fix
  • 5,575
  • 3
  • 28
  • 30