问题
After I tap table cells, I am getting a delay of 4 to 5 seconds for the alert view to display. Below is the code
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)
}
How to avoid this delay?
回答1:
When we deal with UI, then its important that it must be done on main tread. So just copy your code of showing alert and paste in dispatch main thread block.
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:
Write code in main queue to present UIAlertViewController.
DispatchQueue.main.async {
//Write your code here.
}
来源:https://stackoverflow.com/questions/41541444/how-to-remove-delay-from-uialertcontroller