开发者

The delegate method "clickedButtonAtIndex:" is not called

开发者 https://www.devze.com 2022-12-24 06:45 出处:网络
I have created an alert view with two buttons using the following code: UIAlertView *alertView = [[UIAlertView alloc] initWithTitle: title

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 ad开发者_开发技巧vance,

Sagiftw


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.


Try setting the delegate to self instead of nil.


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.


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消