2013-02-02 142 views
2

我在菜单中有一个按钮,当它被触摸时,弹出一个带有两个按钮“Cancel”和“Yes”的警报消息。这是我对警报代码:iOS alertview操作按钮

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

是否可以添加到按钮“Yes”的行动?

回答

11

在代码中设置的UIAlertView中代表:

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

正如你所设定的委托自我,写在同一个类中的委托功能,如下图所示:

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

您需要实现UIAlertViewDelegate

,并添加以下...

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

如果你有多个UIAlertViews,你应该设置标签来描述哪一个被调用。 –

0

是很容易。看到你现在设置为零的那个叫做“委托”的论点?将其设置为一个对象...通常是“自我”,如果你从你的视图控制器调用它,然后实现UIAlertViewDelegate的选择器。

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

@interface MyViewController() <UIAlertViewDelegate> 
@end 

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