iOS:didSelectRowAt 索引路径仅适用于第二次点击
Posted
技术标签:
【中文标题】iOS:didSelectRowAt 索引路径仅适用于第二次点击【英文标题】:iOS: didSelectRowAt Index Path only works on second click 【发布时间】:2019-01-08 09:16:49 【问题描述】:我正在为我的 xcode 项目中的一个问题而苦苦挣扎。我在表格视图中显示自定义单元格并使用didSelectRowAt indexPath:
显示详细视图。它以我想要的方式工作,但奇怪的是只在第二次点击时。
我对编程相当陌生,非常感谢您的帮助。非常感谢!
我检查了我不是偶然使用didDeselectRow at
。我还通过***尝试找到解决方案,这是我能找到的最接近我的问题的解决方案。但我使用的是didSelectRow at
。
// 这是用户点击单元格时的代码:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
// Pop Up Variables
var id:String = tasks[indexPath.row].task_id!
var title:String = tasks[indexPath.row].task_title!
var type:String = tasks[indexPath.row].task!
var desc:String = tasks[indexPath.row].task_desc!
var action:String = "Dismiss"
present(detailVC!, animated: true, completion:
self.detailVC!.setPopup(withTaskId: id, withTitle: title, withType: type, withDesc: desc, withAction: action)
)
//这里只是说明一下,我在文档顶部设置切换到另一个视图控制器。
// 显示弹窗 var detailVC:TaskDetailViewController?
override func viewDidLoad()
super.viewDidLoad()
// Set up the task detail view controller
detailVC = storyboard?.instantiateViewController(withIdentifier: "TaskDetailVC") as! TaskDetailViewController?
detailVC?.delegate = self
detailVC?.modalPresentationStyle = .overCurrentContext
// Conform to the table view protocols
tableView.dataSource = self
tableView.delegate = self
// Set Self as delegate for model and call getTasks
// Get the Tasks from the Task Model
model.delegate = self
model.getTasks()
仅在我第二次点击一行后才会显示详细信息视图。不是第一次?
【问题讨论】:
在 Swift 中尽量避免 snake case:task_id
—> taskId
或更好,只需 id
您很可能有另一个手势识别器与点击单元格冲突。
请确认- 用力按一个单元格并检查,是否点击了第一次尝试?
可能从设置断点开始(或者如果您不确定如何设置断点,只需一条日志消息)并确保每次点击单元格时都正确调用didSelect
。如果您可以向我们提供有关您的设置/视图层次结构的更多详细信息,这也会有所帮助。例如,您的tableView
是***视图吗?
在我刚接触 ios 时发生过好几次,因为我使用了func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath)
。这可能不是你的情况,但正如其他人建议的那样,在不同的地方放置断点。或者你可以上传整个项目,我们可以尝试解决这个问题
【参考方案1】:
几年前我遇到过这个问题,不知道它今天仍然存在。
我通过使用 GCD 在主线程中封装 didSelectRowAt
中的所有逻辑来解决它。你可以看看这些:
https://***.com/a/27907119/6642629
https://***.com/a/26183438/6642629
您可以尝试以下方法:
斯威夫特 4
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
DispatchQueue.main.async
var id:String = tasks[indexPath.row].task_id!
var title:String = tasks[indexPath.row].task_title!
var type:String = tasks[indexPath.row].task!
var desc:String = tasks[indexPath.row].task_desc!
var action:String = "Dismiss"
present(detailVC!, animated: true, completion:
self.detailVC!.setPopup(withTaskId: id, withTitle: title, withType: type, withDesc: desc, withAction: action)
)
【讨论】:
非常感谢,它成功了,我只需要在你的代码上使用 self 关键字就可以让它工作,但它现在工作了。再次非常感谢。【参考方案2】:只需将 InterfaceBuilder 中 UITableView 的 Selection
从 Multiple Selection
更改为 Single Selection
即可。
然后您应该自己处理每一行的选定状态(使用模型中的字段或为背景设置颜色等)
【讨论】:
以上是关于iOS:didSelectRowAt 索引路径仅适用于第二次点击的主要内容,如果未能解决你的问题,请参考以下文章
didSelectRowAt 索引的 indexPath 错误