【发布时间】:2019-09-17 16:27:45
【问题描述】:
我正在尝试从 TableView 多个复选标记中保存和加载选项。
我已准备好代码,但我不知道如何保存选择。以及如何在列表开头加载选择。
我的密码:
var selectedCells = [IndexPath]()
var selectedAreas = [String]()
var Areas = [] //my text for the cells..
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return Areas.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
let cell = tableView.dequeueReusableCell(withIdentifier: "cell")!
cell.textLabel?.text = Areas[indexPath.row]
cell.accessoryType = selectedCells.contains(indexPath) ? .checkmark : .none
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let selectedCell = tableView.cellForRow(at: indexPath)
selectedCells.append(indexPath)
if selectedCell?.accessoryType == .checkmark {
if let indexremove = selectedAreas.firstIndex(of: (Areas[indexPath.row])) {
selectedAreas.remove(at: indexremove)
}
selectedCell?.accessoryType = .none
print(selectedCells)
print(selectedAreas)
print("remove ")
selectedCells = selectedCells.filter {$0 != indexPath}
} else {
print(selectedCells)
print(selectedAreas)
print("add")
selectedAreas.append(Areas[indexPath.row])
selectedCell?.accessoryType = .checkmark
}
}
【问题讨论】:
-
最简单的方法是将单元格的标识符(例如 indexPath)保存为 UserDefaults 中所选 indexPath 的数组并检索它们。到目前为止,它并不是理想的解决方案,因为它假定索引路径始终相同,并且底层数据模型永远不会改变。
-
如果您能帮助我并在我的代码上更改它,我将非常高兴。
-
非常可疑,同样的问题被不同的账户stackoverflow.com/questions/57973633/…
标签: ios arrays swift uitableview multi-select