首页 > 解决方案 > 斯威夫特 | 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
    }

}

标签: iosswiftuitableview

解决方案


发生该错误是因为您始终在 中切换checked状态。因此,每当为此行调用时,都会切换状态。configureCheckmarkcellForRow

实际上不需要额外的方法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

并考虑使用结构而不是类。


推荐阅读