在UIAlertView上同时点击2个按钮会冻结应用程序

时间:2014-11-12 14:28:22

标签: ios uialertview freeze

我有这个错误:如果我在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;
    }
}

2 个答案:

答案 0 :(得分:2)

是的,可以点击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
   }
}

答案 1 :(得分:1)

在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];
}