gpt4 book ai didi

ios - 在 shouldPerformSegue 中显示 UIAlertViewController

转载 作者:可可西里 更新时间:2023-11-01 02:08:50 36 4
gpt4 key购买 nike

在我的项目中,我设置了一个 UITableView,它的单元格绑定(bind)到一个 segue,将用户带到另一个 ViewController,其中单元格的数据得到详细显示。但是,并非所有单元格都应执行转接(例如,单元格中显示的记录无效且不应显示,因此无需转到详细信息 Controller )。

为此任务,我使用了 UIViewController 的 shouldPerformSegue 方法:(我假设在下面的代码片段中,表中的第二行是不应该执行转场的那一行)

override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
guard let indexPath = tableView.indexPathForSelectedRow else {
return false
}

if indexPath.row == 1 {
let alert = UIAlertController(
title: "Invalid record",
message: "This record is malformed, can't display the data.",
preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Okay :(", style: .default))
present(alert, animated: true, completion: nil)
return false
} else {
return true
}
}

这会导致一些奇怪的行为:每当我点击第二行时,警报只会在一两秒后显示,有时甚至会在点击后五秒显示,有时它根本不会显示,直到我执行其他一些 UI 操作比如滚动表格 View 或再次点击。

经过反复试验,我找到了一个解决方案:当我将它强制到主线程时,在点击“错误”单元格后,警告立即显示:

DispatchQueue.main.async {
present(alert, animated: true, completion: nil)
}

这对我来说是违反直觉的,因为 prepareForSegue 方法已经在主线程上执行了。所以我的问题是:UIAlertController 的不稳定行为从何而来,我是否需要在主线程上强制显示它,还是我做错了什么?

最佳答案

并不是说 shouldPerformSegue 不在主队列中,而是这个函数参与了 segue 过程,所以此时提出另一个观点是个坏主意。

通过使用异步调度,您允许当前的 segue 进程在出现警报之前完成(或在这种情况下被中止)。

我认为这是解决您的问题的合理方法。

关于ios - 在 shouldPerformSegue 中显示 UIAlertViewController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41633978/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com