我正在做一个屏幕,其中有一个带有开关的单元格列表,如下图所示;我有一个结构,其中保存单元格的标签和开关状态值。将该结构加载到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所触摸的单元格?
您不应在单元格中存储/读取任何状态。但首先要注意的是:
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)
}