UIAlertView不会调用其方法目标c

时间:2014-12-05 04:05:41

标签: objective-c uialertview

这是我的代码。我正在研究BAC计算器应用程序。我正在尝试添加一个警告,要求用户确认他们何时添加饮料(表明他们只喝了一杯标准饮料)。确认后,我希望它增加BAC(这是一个全局浮点变量),然后更新显示用户的BAC(self.BACNum.text)的视图控制器上的标签。

问题是当用户按下OK时UIAlert没有响应。请帮忙!

- (IBAction)AddDrink:(id)sender {
UIAlertView *addDrinkAlert = [[UIAlertView alloc] initWithTitle:@"Confirm adding one standard drink." message:@"A standard drink is 12oz beer, 5oz wine, or a 1.5 oz shot of 80 proof liquor." delegate:nil cancelButtonTitle:@"Cancel" otherButtonTitles:@"Ok", nil];


[addDrinkAlert show];

}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{

    if (buttonIndex == 1)
    {

        if ([gender isEqualToString:@"Male"]) {
            genderConst = 0.68;
        }
        else {
            genderConst = 0.55;
        }

        BAC += (2.84)/([weight floatValue]*genderConst);
        self.BACNum.text = [NSString stringWithFormat:@"%.3f", BAC];

        [NSTimer scheduledTimerWithTimeInterval: 60.0 target:self selector:@selector(metabolize:) userInfo:nil repeats: YES];

        [self.navigationController popViewControllerAnimated:YES];

        return;
    }

    else {

        return;
    }

}

3 个答案:

答案 0 :(得分:0)

delegate:nil

有你的问题。您应该在这里传递一个符合UIAlertViewDelegate协议并实现-alertView:clickedButtonAtIndex:方法的对象。在您的情况下,它是self

答案 1 :(得分:0)

设置代理delegate:self

UIAlertView *addDrinkAlert = [[UIAlertView alloc] initWithTitle:@"Confirm adding one standard drink." message:@"A standard drink is 12oz beer, 5oz wine, or a 1.5 oz shot of 80 proof liquor." delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Ok", nil];


[addDrinkAlert show];

答案 2 :(得分:0)

我遇到了同样的问题,当我为iOS 8编译了我的代码之后。我发现很多东西后我才知道iOS 8,我们必须使用AlertController,Apple从现在开始停止支持UIAlertView。这就是为什么你的alertViewDelegate方法无效。

请尝试以下代码,这肯定会有效。

UIAlertController *alertController=[UIAlertController alertControllerWithTitle:@"Confirm adding one standard drink." message:@"A standard drink is 12oz beer, 5oz wine, or a 1.5 oz shot of 80 proof liquor." preferredStyle:UIAlertControllerStyleAlert];

UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action)
                                     {
                                         // code for OK Button click
                                     }];
[alertController addAction:okAction];
[self presentViewController:alertController animated:YES completion:nil];