按钮上的iOS alertview操作

时间:2013-02-02 17:50:01

标签: ios xcode alertview

我在菜单中有一个按钮,当触摸时,会弹出一个带有两个按钮的警告消息:" Cancel"和" Yes"。这是警报的代码:

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Exit game"
                                                message:@"Are you sure?"
                                               delegate:nil
                                      cancelButtonTitle:@"Cancel"
                                      otherButtonTitles:@"Yes", nil];
[alert show];

是否可以向按钮添加操作" Yes"?

3 个答案:

答案 0 :(得分:11)

在您的代码中设置UIAlertView委托:

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Exit game" message:@"Are you sure?" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Yes", nil]; [alert show];

当你将委托设置为self时,在同一个类中编写委托函数,如下所示:

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
if (buttonIndex == 1) { // Set buttonIndex == 0 to handel "Ok"/"Yes" button response
    // Cancel button response
    }}

答案 1 :(得分:1)

您需要实施UIAlertViewDelegate

并添加以下内容......

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) {
        // do stuff
    }
}

答案 2 :(得分:0)

是的,这很容易。看到你现在设置为nil的名为“delegate”的参数?将其设置为对象...如果从视图控制器调用它,则通常为“self”,然后为UIAlertViewDelegate实现选择器。

您还需要声明视图控制器符合UIAlertViewDelegate协议。这样做的好地方是视图控制器的“私有”延续类。

@interface MyViewController() <UIAlertViewDelegate>
@end

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
   NSLog(@"Button pushed: %d", buttonIndex);
}
相关问题