6

我使用以下代码创建了一个带有两个按钮的警报视图:

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

单击其中一个按钮时,我想运行一些代码。为此,我在 delegate.m 文件中添加了以下方法:

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

但是当我按下任何一个按钮时都不会调用这个方法!有人能告诉我为什么吗?

提前致谢,

萨吉夫特

4

5 回答 5

40
delegate:nil

如果您指定没有委托,警报视图将如何关联委托?将该部分替换为

delegate:self

反而。

于 2010-03-29T13:02:56.753 回答
3

尝试将委托设置为 self 而不是 nil。

于 2010-03-29T13:02:19.140 回答
2

我从 UITextField 委托方法调用 UIAlertView 的dismissWithClickedButtonIndex:animated:方法,因为我也想处理键盘返回键:

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

这种方法alertView:clickedButtonAtIndex:即使您设置了正确的委托,也永远不会被调用。相反, alertView:didDismissWithButtonIndex:确实被调用了。所以改为实现这个方法:

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

如果您只想处理警报视图的按钮,则首先调用 clickedButtonAtIndex,然后调用 didDismissWithButtonIndex。

于 2014-07-15T09:02:22.490 回答
0

在 .h 中放置 UIActionSheetDelegate 并在 .m 中创建 alertView 时将委托设置为 self 而不是在上述情况下完成

于 2012-11-07T05:04:06.990 回答
0

这个问题的正确答案是delegate:nil。但是,如果委托已经设置为 self,并且clickedButtonAtIndex仍然无法正常工作,请尝试[self.navigationController popViewControllerAnimated:YES];在显示 alertview 后检查您是否正在弹出另一个视图控制器 ( )。这也可能导致clickedButtonAtIndex不被调用。这就是发生在我身上的事情。

希望这可以帮助某人。

于 2015-11-17T07:46:16.760 回答