如何从UIAlertController中删除延迟?

点击表格单元格后,我将显示4到5秒的延迟,以显示警报视图。 以下是代码

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){ let cell = tableView.cellForRow(at: indexPath)! let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .alert) let ok = UIAlertAction(title: "Ok", style: .default, handler: { (action) -> Void in let cell = tableView.cellForRow(at: indexPath)! }) let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: { (action) -> Void in }) alertController.addAction(ok) alertController.addAction(cancel) present(alertController, animated: true, completion: nil) } 

如何避免这种延迟?

当我们处理UI时,重要的是它必须在主要步骤上完成。 因此,只需复制显示警报的代码并粘贴到调度主线程块中。

 DispatchQueue.main.async { let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .alert) let ok = UIAlertAction(title: "Ok", style: .default, handler: { (action) -> Void in let cell = tableView.cellForRow(at: indexPath)! }) let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: { (action) -> Void in }) alertController.addAction(ok) alertController.addAction(cancel) present(alertController, animated: true, completion: nil) } 

在主队列中编写代码以呈现UIAlertViewController。

 DispatchQueue.main.async { //Write your code here. }