Наиболее эффективное и надежное решение - сохранить состояние isSelected
в модели данных.
Используйте структуру в качестве модели данных и добавьте члена isSelected
вместе с другой необходимой вам информацией.
struct Model {
var isSelected = false
var someOtherMember : String
// other declarations
}
В cellForRow
установите флажок в соответствии с isSelected
member
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) // use always the passed tableView instance
let model = itemsInSections[indexPath.section][indexPath.row]
cell.accessoryType = model.isSelected ? .checkmark : .none
cell.textLabel?.text = model.someOtherMember
return cell
}
В didSelectRowAt
и didDeselectRowAt
обновите модель и перезагрузите строку
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
itemsInSections[indexPath.section][indexPath.row].isSelected = true
tableView.reloadRows(at: [indexPath], with: .none)
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
itemsInSections[indexPath.section][indexPath.row].isSelected = false
tableView.reloadRows(at: [indexPath], with: .none)
}
Никогда не использует дополнительный массив для сохранения путей индекса. Не делай этого.