ios - 我有一个2键UIAlertView,我怎么知道按下了哪个按钮?

时间:2012-11-28 17:40:39

标签: ios ios5 uialertview

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

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>

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

谢谢!

3 个答案:

答案 0 :(得分:5)

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

E.g。

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

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

取消按钮的索引为0。

答案 1 :(得分: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
    }
}

答案 2 :(得分:2)

message.delegate = self;
...

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

并且必须声明该类符合UIAlertViewDelegate协议。