Я делаю экран, где есть список ячеек с переключателем, как на картинке ниже; У меня есть структура, где сохранить метку ячейки и значение состояния переключателя. Эта структура загружается в: 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
}
}
, хотя при сохранении правильных значений в массив состояний переключателей (источник) визуальное состояние переключателей кратных также меняется, хотя ячейки, где никогда коснитесь.
Как я могу изменить свой код, чтобы выбрать и изменить только затронутую ячейку?
![enter image description here](https://i.stack.imgur.com/orJvZ.png)