6

I have created an alert view with two buttons using the following code:

UIAlertView *alertView = [[UIAlertView alloc] initWithTitle: title 
message: msg delegate:nil cancelButtonTitle:@"Replay" otherButtonTitles:@"Highscore", nil];
[alertView show];

I want to run some code when one of the buttons is clicked. In order to do so, I have added the following method to the delegate.m file:

 - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
 if (buttonIndex==0) //Run some code 
 else //Other code
 }

But this method is not called when I press either of the buttons! Can someone tell me why?

Thanks in advance,

Sagiftw

Sagiftw
  • 1,658
  • 4
  • 21
  • 25

5 Answers5

40
delegate:nil

how will the alert view associate a delegate if you specified there will be no delegates? Replace that part with

delegate:self

instead.

kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
3

Try setting the delegate to self instead of nil.

2

I was calling UIAlertView's dismissWithClickedButtonIndex:animated: method from UITextField delegate method because I wanted to handle the keyboard return key as well:

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (textField.tag == 1001) {
        [textField resignFirstResponder];
        [_alert dismissWithClickedButtonIndex:1 animated:YES];
    }
    return YES;
}

This way method alertView:clickedButtonAtIndex: never gets called even if you set up proper delegate. Instead alertView:didDismissWithButtonIndex: does get called. So implement this method instead:

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    // your code here
}

If you just want to handle alert view's buttons only, those first call clickedButtonAtIndex and then didDismissWithButtonIndex.

frin
  • 4,474
  • 3
  • 31
  • 23
0

in .h put UIActionSheetDelegate and in .m while creating a alertView put the delegate to self not nil as being done in the above case

Kasaname
  • 1,491
  • 11
  • 15
0

The correct answer for this question is delegate:nil. But in case that the delegate is already set to self, and the clickedButtonAtIndex is still not working, try checking if you are popping another view controller ([self.navigationController popViewControllerAnimated:YES];) after showing the alertview. This can also result to clickedButtonAtIndex not being called. This is what happened to me.

Hope this helps someone.

Gellie Ann
  • 439
  • 1
  • 6
  • 10