如何在UIAlertView中为按钮编写事件处理程序?

Rav*_*avi 22 objective-c uialertview ios

假设我在obj c中有如下的警报视图

UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"title" message:@"szMsg" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:@"download"];
        [alert show];
        [alert release];
Run Code Online (Sandbox Code Playgroud)

现在我们在警报视图上有2个按钮(确定并下载),如何为下载一个编写事件处理程序?

Che*_*ara 46

首先,您需要将UIAlertViewDelegate添加到头文件中,如下所示:

头文件(.h)

@interface YourViewController : UIViewController<UIAlertViewDelegate> 
Run Code Online (Sandbox Code Playgroud)

实施文件(.m)

UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"title" message:@"szMsg" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:@"download"];
        [alert show];
        [alert release];

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0)
    {
        //Code for OK button
    }
    if (buttonIndex == 1)
    {
        //Code for download button
    }
}
Run Code Online (Sandbox Code Playgroud)


zou*_*oul 5

现在大多数iOS设备都拥有使用块支持的极端版本​​,使用笨拙的回调API处理按钮按钮是不合时宜的.块是可行的方法,例如参见GitHub上Lambda Alert类:

CCAlertView *alert = [[CCAlertView alloc]
    initWithTitle:@"Test Alert"
    message:@"See if the thing works."];
[alert addButtonWithTitle:@"Foo" block:^{ NSLog(@"Foo"); }];
[alert addButtonWithTitle:@"Bar" block:^{ NSLog(@"Bar"); }];
[alert addButtonWithTitle:@"Cancel" block:NULL];
[alert show];
Run Code Online (Sandbox Code Playgroud)