ios - 斯威夫特 | UIViewTable 滚动离开屏幕时更改复选标记
问题描述
我在 TableView 中有一个 TableViewCells (todoList.items) 列表。我可以轻松地切换复选标记并且有效。但是,当单元格滚动到表格视图的边缘时,复选标记会意外地自行切换。
在我的视图控制器中
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ChecklistItem", for: indexPath)
let item = todoList.items[indexPath.row]
configureText(for: cell, with: item)
configureCheckmark(for: cell, with: item)
return cell
}
// **EDIT**
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) {
let item = todoList.items[indexPath.row]
configureCheckmark(for: cell, with: item)
tableView.deselectRow(at: indexPath, animated: true)
}
}
func configureCheckmark(for cell: UITableViewCell, with item: ChecklistItem) {
cell.accessoryType = item.checked ? .checkmark : .none
item.toggleChecked()
}
// **END EDIT**
TodoList.swift
class TodoList {
var items: [ChecklistItem] = []
init() {
// Create some demo items
items.append(ChecklistItem(text: "Take a jog"))
items.append(ChecklistItem(text: "Watch a movie"))
items.append(ChecklistItem(text: "Code an app"))
items.append(ChecklistItem(text: "Walk the dog"))
items.append(ChecklistItem(text: "Study design patterns"))
}
func newItem() -> ChecklistItem {
items.append(ChecklistItem(text: "NEW ITEM"))
return items[items.count-1]
}
}
ChecklistItem.swift
class ChecklistItem {
var text = ""
var checked = true
init(text: String) {
self.text = text
}
func toggleChecked() {
checked = !checked
}
}
解决方案
发生该错误是因为您始终在 中切换checked
状态。因此,每当为此行调用时,都会切换状态。configureCheckmark
cellForRow
实际上不需要额外的方法configureCheckmark
。放入行以设置复选标记cellForRow
但不要更改状态。
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ChecklistItem", for: indexPath)
let item = todoList.items[indexPath.row]
configureText(for: cell, with: item)
cell.accessoryType = item.checked ? .checkmark : .none
return cell
}
在模型中didSelectRowAt
切换checked
并重新加载行
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
todoList.items[indexPath.row].checked.toggle()
tableView.reloadRows(at: [indexPath], with: .none)
}
中的方法toggleChecked()
也是ChecklistItem
多余的。中有一个toggle()
方法Bool
。
并考虑使用结构而不是类。
推荐阅读
- css - 有什么方法可以对齐 divi 联系表中的复选框?自定义 CSS 建议?
- python - discord py bot 触发两次 on_member_update 函数
- javascript - JavaScript - 对象属性作为函数结果,如 Array.length
- list - 我的列表 if,else 语句只返回“if”语句
- php - 引用 foreach 循环中的先前值
- python - 如何在 csv 文件的列中填充空值?
- c - 需要帮助 C 中的故障排除程序
- r - Jaccard 分析相似度
- python - 元素共享类名并动态移动 Python / BS4
- python - 在 Python 中将整数列表写入文件的最紧凑方法