首页 > 解决方案 > 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)
    }
}

标签: iosswiftuitableview

解决方案


细胞被重复使用。例如,最有效的解决方案是向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。如果可以插入、删除或移动单元格,额外的数组就会变得烦人。


推荐阅读