UIAlertView无法响应按钮事件

时间:2014-01-03 01:56:02

标签: ios uialertview

第一次使用UIAlertViews,我无法弄清楚为什么这不起作用。当我点击任一按钮时,警报会关闭,但没有 NSLog 输出。我究竟做错了什么?我无法弄清楚。谢谢!

·H

@interface LoginViewController : UIViewController <UIAlertViewDelegate>

@end

的.m

- (IBAction)resetPassword:(UIButton *)sender {

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Password Reset"
                                                      message:@"A temporary password will be sent to you at the address we have on file."
                                                     delegate:nil
                                            cancelButtonTitle:@"Cancel"
                                        otherButtonTitles:@"Reset Password", nil];
    [alert show];

}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) NSLog(@"button 0");
    if (buttonIndex == 1) NSLog(@"button 1");
}

2 个答案:

答案 0 :(得分:4)

看起来您从未在UIAlertView上设置委托。它应该是:

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Password Reset"
                                                  message:@"A temporary password will be sent to you at the address we have on file."
                                                 delegate:self
                                        cancelButtonTitle:@"Cancel"
                                    otherButtonTitles:@"Reset Password", nil];

这样,当用户点击按钮时,UIAlertView就可以调用您的方法- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex

答案 1 :(得分:2)

您将delegate设置为零。您需要将其设置为控制器实例,如下所示:

- (IBAction)resetPassword:(UIButton *)sender {

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Password Reset"
                  message:@"A temporary password will be sent to you at the address we have on file."
                  delegate:self
                  cancelButtonTitle:@"Cancel"
                  otherButtonTitles:@"Reset Password", nil];
    [alert show];

}

如果您从未向UIAlertView提供作为委托的对象,那么实现-alertView:clickedButtonAtIndex:委托方法没什么用。