2010-03-29 156 views
6

我已经创建了一个警报视图使用下面的代码两个按钮:委托方法“clickedButtonAtIndex:”不叫

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 
} 

但是这种方法不叫当我按下任一按钮! 有人能告诉我为什么吗?

由于提前,

Sagiftw

回答

39
delegate:nil 

如果您指定不存在委托,那么警报视图如何关联委托?将该部分替换为

delegate:self 

改为。

+0

感谢您的帮助!我忘了! =) – Sagiftw 2010-03-29 13:25:27

+0

Thanx我也被遗忘了。 – iBapu 2012-07-09 11:04:58

3

尝试委托设置自我,而不是零。

0
在.H

把UIActionSheetDelegate并同时创造一个.M把alertView委托自我不为零作为在上述情况下

2

我打电话UIAlertView中的dismissWithClickedButtonIndex正在做的:动画:从的UITextField委托方法方法因为我想处理键盘回车键,以及:

- (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。

0

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

希望这可以帮助别人。