【发布时间】:2020-06-02 13:52:08
【问题描述】:
我正在做一个屏幕,其中有一个带有开关的单元格列表,如下图所示;
我有一个结构,其中保存单元格的标签和开关状态值。这个结构体被加载到:var source: [StructName] = [],然后源值被赋予 UITableView 单元格。
问题是当触摸一个单元格时,函数:func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)change multiples cells 同时切换状态。
我尝试通过实现以下功能来解决这个问题:
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
}
}
虽然将正确的值保存到开关状态数组(源)中,但多个开关的视觉状态也会发生变化,即使从未接触过的单元格也是如此。
如何更改我的代码以选择和更改仅触摸的单元格?
【问题讨论】:
标签: ios swift uitableview swift5 uiswitch