Swift 5 | didSelectRowAt正在同时选择两个单元格

问题描述 投票:0回答:1

我正在做一个屏幕,其中有一个带有开关的单元格列表,如下图所示;我有一个结构,其中保存单元格的标签和开关状态值。将该结构加载到var source: [StructName] = [],然后将源值分配给UITableView单元格。

问题是,当触摸一个单元格时,功能:func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)更改多个单元格会同时切换状态。我尝试通过实现以下功能来解决此问题:

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    tableView.deselectRow(at: indexPath, animated: true)

    let cell = tableView.cellForRow(at: indexPath) as! CustomTableViewCell
    for n in 0..<source.count{ // This loop search for the right cell by looking at the cell label text and the struct where the state of the switch is saved
        if cell.label.text! == source[n].Label{
            // If the label text is equal to the position where the values is saved (is the same order that the cells are loaded in the UITableView) then a change the state of the switch
            let indexLabel = IndexPath(row: n, section: 0)
            let cellValues = tableView.cellForRow(at: indexLabel) as! CustomTableViewCell
            if cellValues.switchButton.isOn {
                cellValues.switchButton.setOn(false, animated: true)
                source[n].valor = cellValues.switchButton.isOn
            } else {
                cellValues.switchButton.setOn(true, animated: true)
                source[n].valor = cellValues.switchButton.isOn
            }
            break
        }
    }

尽管已将正确的值保存到开关状态数组(源),但即使从不接触单元,多个开关的视觉状态也会改变。

如何更改代码以选择并更改only所触摸的单元格?

enter image description here

ios swift uitableview swift5 uiswitch
1个回答
2
投票

您不应在单元格中存储/读取任何状态。但首先要注意的是:

  • 为什么循环遍历所有值?您应该可以通过indexPath.row
  • 直接访问数据模型中的行
  • 您应该只修改模型数据,而不是单元格
  • 然后您告诉表格视图重新加载单元格,然后单元格将要求模型显示正确的数据。

我建议以下内容:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    tableView.deselectRow(at: indexPath, animated: true)

    let row = indexPath.row
    source[row].valor.toggle()
    tableView.reloadRows(at:[indexPath], with:.automatic)
}
© www.soinside.com 2019 - 2024. All rights reserved.