首页 > 解决方案 > 使用复选标记附件发出选择行

问题描述

我有一个从 JSON 获取数据的 tableView。它包含一个名为 Marked 的字段:

struct Example: Decodable {

    let marked: Int
}

Marked 可以等于 1 或 2。如果为 2,则在加载 tableView 时应出现一个复选标记附件,如果为 1,则应自动选择该行,则不应出现附件。

在 cellForRowAt 我使包含 2 的记录的单元格显示一个复选标记:

let Structure: Example

    if (Structure.marked == 2) {
        cell.accessoryType = .checkmark
    } else {
        cell.accessoryType = .none
    }

问题是,取消选择时,我被迫选择该行两次,就好像它还没有复选标记以使复选标记消失一样。

    override func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
        unselect()
        tableView.cellForRow(at: indexPath)?.accessoryType = .none
      }

是否也可以自动选择复选标记行?

标签: swift

解决方案


将结构成员声明为变量

struct Example: Decodable {
    var marked: Int
}

仅使用didSelectRowAt(和 delete didDeselectRowAt),在方法中切换结构中的值并重新加载行,datasource表示数据源数组。

基本上永远不要cellForRow在不同时更新模型的情况下修改单元格

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if datasource[indexPath.row].marked == 2 {
       datasource[indexPath.row].marked = 1
       unselect()
    } else {
       datasource[indexPath.row].marked = 2
       select()
    }
    tableView.reloadRows(at: [indexPath], with: .none)
}

如果您负责后端,请发送markedas BoolInt非常麻烦。


推荐阅读