The delegate method “clickedButtonAtIndex:” is not called

女生的网名这么多〃 提交于 2019-12-13 11:45:46

问题


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


回答1:


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.




回答2:


Try setting the delegate to self instead of nil.




回答3:


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.




回答4:


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




回答5:


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.



来源:https://stackoverflow.com/questions/2537993/the-delegate-method-clickedbuttonatindex-is-not-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!