在iPhone的警报视图

shr*_*evi 25 iphone cocoa-touch objective-c

我是iPhone应用程序开发的新手.我想用2个按钮设计一个警报视图:OKCancel.当用户触摸OK按钮时,我将打印出一条消息hello.当他们触摸Cancel按钮时,我会打印出来cancel.

请帮忙; 我该怎么做呢?

Ste*_*son 63

要显示警报:

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Do you want to say hello?"
                                                message:@"More info..."
                                               delegate:self
                                      cancelButtonTitle:@"Cancel"
                                      otherButtonTitles:@"Say Hello",nil];
[alert show];
[alert release];
Run Code Online (Sandbox Code Playgroud)

要响应点击的按钮:

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {
        NSLog(@"Cancel Tapped.");
    }
    else if (buttonIndex == 1) {
        NSLog(@"OK Tapped. Hello World!");
    }
}
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅UIAlertView类参考UIAlertView代表协议参考.

  • 您的答案是否也应该包含.h文件中<UIAlertViewDelegate>的必要性?我意识到你引用了类和委托协议,但很容易想象OP跳过那部分:( (2认同)

kra*_*ver 27

由于所选答案已弃用,以下是新解决方案:

UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"My Alert"
                               message:@"This is an alert."
                               preferredStyle:UIAlertControllerStyleAlert];

UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault
   handler:^(UIAlertAction * action) {}];

[alert addAction:defaultAction];
[self presentViewController:alert animated:YES completion:nil];
Run Code Online (Sandbox Code Playgroud)

iOs开发人员指南中所示.


Nie*_*tle 5

使用以下代码段显示提醒

UIAlertView *alert = [[UIAlertView alloc]
   initWithTitle:@"Make an informed choice"
   message:nil
   delegate:self
   cancelButtonTitle:@"Cancel"
   otherButtonTitles:@"OK", nil];
[alert show];

代表被设置为自我,因此当警报被取消时,我们自己的班级将收到回电.委托必须实现UIAlertViewDelegate协议.

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

   if (buttonIndex == 1) {
      // Do it!
   } else {
      // Cancel
   }
}