ios - didSelectRowAt 未按预期工作
问题描述
我在为单元格打勾时遇到问题。我在单元格中放置了一个检查标签。当用户点击单元格时,标签显示●,当用户再次点击单元格时,它应该显示○。但是,当我点击一个单元格时,例如索引路径 0,10,然后 0,10 和 0,5 都会显示●。为什么会这样?任何帮助表示赞赏。
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if isEditingSetlist{
if let cell = booklistDetailTableView.cellForRow(at: indexPath) as? BooklistTableViewCell {
if cell.checkLabel.text == "●"{
cell.checkLabel.text = "○"
}else{
cell.checkLabel.text = "●"
}
}
selectedRows.append(indexPath.row)
}
}
解决方案
细胞被重复使用。例如,最有效的解决方案是向isSelected
数据模型添加一个属性
struct Model {
var isSelected = false
// other properties
}
在cellForRowAt
相应地设置复选标记(dataSource
代表数据源数组)
let item = dataSource[indexPath.row]
cell.checkLabel.text = item.isSelected ? "●" : "○"
在didSelectRow
切换isSelected
并重新加载行(调用cellForRowAt
)
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if isEditingSetlist{
dataSource[indexPath.row].isSelected.toggle()
tableView.reloadRows(at: [indexPath], with: .automatic)
}
}
而忘记selectedRows
。如果可以插入、删除或移动单元格,额外的数组就会变得烦人。
推荐阅读
- reactjs - 如何让 AWS Amplify 的 DataStore 在 React 中的用户会话之间同步?
- python - 如何返回要在另一个函数中使用的文字文本字符串
- rabbitmq - NestJS:有没有办法从外部调用微服务rabbitmq
- javascript - 我无法弄清楚为什么当 localhost:3000 对简单的 API 工作正常时我无法访问 localhost:5000
- sql - 使用 group by 子句连接结果
- android - Firebase OTP 身份验证返回网页以检查机器人
- javascript - 从javascript调用c#程序
- reactjs - Mobx 观察可观察对象数组
- solr - Solr fetchIndex 命令在分片节点上莫名其妙地失败
- python - Django ORM 在循环中过滤 SUM 不同的相关对象