UIAlertView 延迟或不显示

UIAlertView delay or not showing

我已经多次使用 UIAlertView 没有问题,但是这次我无法使其正常工作。 (简单)代码如下:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    alert = [[UIAlertView alloc]initWithTitle:@""
                                      message:[NSString stringWithFormat: @"Reload data ?"]
                                     delegate:self
                            cancelButtonTitle:@"Yes"
                            otherButtonTitles:@"Cancel", nil];    
    [alert show];
    NSLog(@"executed");
}

如果我触摸 TableView 的一行,我会出现两种不同的行为:

  1. alertView 在几 (6/7) 秒后显示
  2. 未显示 alertView。在这种情况下,只要我接触任何 屏幕上的某个点会立即显示警报。

在这两种情况下,[alert show] 在第一次触摸后立即执行,因为我在日志屏幕中看到 "executed"。 警报前后,应用程序未执行任何其他操作。

有什么帮助吗?

试试这个

[[NSOperationQueue mainQueue] addOperationWithBlock:^{
        alert = [[UIAlertView alloc]initWithTitle:@""
                                  message:[NSString stringWithFormat: @"Reload data ?"]
                                 delegate:self
                        cancelButtonTitle:@"Yes"
                        otherButtonTitles:@"Cancel", nil];    
       [alert show];
       NSLog(@"executed");
    }];

信不信由你,但 UIAlertView 实际上在 iOS8 中已被弃用。

话虽如此,您仍然可以使用它。对于未来的项目定位 iOS8+,Apple 建议您改用 UIAlertViewController

这是使用 UIAlertViewController 打开应用程序设置的示例:

UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Go to settings" message:@"Do you wish to go to the application settings?" preferredStyle:UIAlertControllerStyleAlert]; ;
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil];
UIAlertAction *settingsAction = [UIAlertAction actionWithTitle:@"Settings" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
}];
[alertController addAction:cancelAction];
[alertController addAction:settingsAction];

[self presentViewController:alertController animated:YES completion:nil];

我也有这个问题,对我来说问题是我同时有两个队列 运行。我在主队列中发生了 UI 更改(所有 UI 更改都需要在主队列中发生)并且我在单独的队列中发生了计算密集型任务。我的初始设置是:

let alert = UIAlertController(title: nil, message: "Custom message", preferredStyle: .alert)
self.present(alert, animated: false, completion: nil)

// perform time intensive task in seperate queue

为了解决这个问题,我将密集型任务移到了完成回调中:

let alert = UIAlertController(title: nil, message: "Custom message", preferredStyle: .alert)
self.present(alert, animated: false, completion: {
    // perform intensive task here
})