同时点击UIAlertView上的两个按钮可冻结应用程序



我有这个错误:如果我同时点击UIAlertView上的两个按钮,UIAlertView代理将不会被调用,整个屏幕将冻结(即使警报视图被取消,也无法点击任何内容)。

以前有人见过这个bug吗?有没有办法限制UIAlertView只能点击一个按钮?

- (IBAction)logoutAction:(id)sender {
        self.logoutAlertView = [[UIAlertView alloc] initWithTitle:@"Logout"
                                                              message:@"Are you sure you want to logout?"
                                                             delegate:self
                                                    cancelButtonTitle:@"No"
                                                    otherButtonTitles:@"Yes", nil];
        [self.logoutAlertView show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if ([alertView isEqual:self.logoutAlertView]) {
        if (buttonIndex == 0) {
            NSLog(@"cancelled logout");
        } else {
            NSLog(@"user will logout");
            [self performLogout];
        }
        self.logoutAlertView.delegate = nil;
    }
}

是的,可以点击UIAlertView上的多个按钮,每次点击都会调用委托方法。但是,这不应该"冻结"你的应用程序。通过代码查找问题。

为了防止处理多个事件,请在处理第一个事件后将UIAlertView的委托属性设置为nil:

- (void)showAlert {
  UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Title" message:@"Message" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
  [alert show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
   // Avoid further delegate calls
   alertView.delegate = nil;
   // Do something
   if (buttonIndex == alertView.cancelButtonIndex) {
     // User cancelled, do something
   } else {
     // User tapped OK, do something
   }
}

在iOS 8:上使用UIAlertController

if ([UIAlertController class])
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Logout" message:@"Are you sure you want to logout?" preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"No" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action)
    {
        NSLog(@"cancelled logout");
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"Yes" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action)
    {
        NSLog(@"user will logout");
        [self performLogout];
    }]];
    [self presentViewController:alert animated:YES completion:nil];
}
else
{
    self.logoutAlertView = [[UIAlertView alloc] initWithTitle:@"Logout"
                                                      message:@"Are you sure you want to logout?"
                                                     delegate:self
                                            cancelButtonTitle:@"No"
                                            otherButtonTitles:@"Yes", nil];
    [self.logoutAlertView show];
}

最新更新