如何消除 UIAlertController 的延迟?

3

当我点击表格单元格时,警报视图需要延迟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)
}

如何避免这种延迟?

动画看起来很慢吗? - Devang Tandel
不是显示控制器,而是需要显示操作方法,即警告控制器中的“确定”和“取消”。 - leaner122
你是否在任何后台线程上? - Rikh
2个回答

17

当我们处理UI时,很重要的一点是必须在主线程上完成。因此,只需将显示警报的代码复制并粘贴到dispatch main thread块中即可。

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)
}

2
这应该是不必要的,因为表视图委托方法只应在主队列上调用。@leaner122,你是否明确地调用了didSelectRowAt委托方法? - rmaddy
1
@rmaddy 你说得对,这应该是不必要的。然而我也遇到了同样的问题,我可以看到在创建UIAlertViewController并呈现它时,它已经在主线程上了,但我遇到了相同的问题,使用dispatch解决了这个问题。很可能是一个错误,而且是一个旧的错误:https://dev59.com/ul8d5IYBdhLWcg3wxklq - bandejapaisa
1
你是绝对正确的,出于某种原因,这确实解决了它。 - CristianMoisei

1
在主队列中编写代码以呈现UIAlertViewController。
DispatchQueue.main.async {
   //Write your code here.
}

你能详细说明一下吗? - leaner122

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接