0

我有这个 2 按钮警报视图:

UIAlertView* message = [[UIAlertView alloc]
                           initWithTitle: @"Delete?" message: @"This business will be deleted permenently." delegate: nil
                           cancelButtonTitle: @"Cancel" otherButtonTitles: @"Delete", nil];

[message show];

我也有这个方法:

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSString *title = [alertView buttonTitleAtIndex:buttonIndex];
    if([title isEqualToString:@"Delete"])
    {
        NSLog(@"Button DELETE was selected.");
    }
    else if([title isEqualToString:@"Cancel"])
    {
        NSLog(@"Button CANCEL was selected.");
    }
}

我将其添加到 .h 文件中:

<UIAlertViewDelegate>

现在,当按下任一按钮时,它只会关闭对话框。可以取消,但我怎么知道何时按下删除按钮?

谢谢!

4

3 回答 3

5

您必须实现– alertView:clickedButtonAtIndex:UIAlertViewDelegate 的方法。您还必须在初始化警报视图时设置委托。

例如

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

   if (buttonIndex == 0) {
        //Do something
   } else if (buttonIndex == 1) {
       //Do something else
   }
}

取消按钮的索引为 0。

于 2012-11-28T17:42:36.460 回答
3

创建警报视图时,您将传递nil给参数。delegate你需要通过self。正如您现在所拥有的,该clickedButtonAtIndex:方法永远不会被调用。

UIAlertView* message = [[UIAlertView alloc]
    initWithTitle: @"Delete?" 
    message: @"This business will be deleted permenently." 
    delegate: self
    cancelButtonTitle: @"Cancel" 
    otherButtonTitles: @"Delete", nil];


- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == alertView.cancelButtonIndex) {
        // Cancel was tapped
    } else if (buttonIndex == alertView.firstOtherButtonIndex) {
        // The other button was tapped
    }
}
于 2012-11-28T17:57:47.197 回答
2
message.delegate = self;
...

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
     NSLog(@"Button %d was clicked", buttonIndex);
}

并且必须声明该类以满足UIAlertViewDelegate协议。

于 2012-11-28T17:46:04.280 回答