首页 > 解决方案 > 如何将 tableview 单元格附件应用于 tableview 记录

问题描述

解释:

我有一个从 JSON 填充的 UITableView。表格视图的目的是让用户选择单独的行记录并显示复选标记附件作为结果。

问题是,虽然我可以让选中的任何一行出现复选标记,但复选标记应用于该行,而不是记录本身。

例如,如果我在 tableview 中有两行并且我选择了第一行,则会对其应用复选标记,但在更新 API 以删除行并重新加载 tableView 后,第一行消失但复选标记应用于什么是第二个记录。

这就是我的 didSelect 方法的样子:

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let section = sections[indexPath.section]
    structure = sections[indexPath.section].items
    let theStructure = structure[indexPath.row]
    tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark

}

这是为 JSON 定义结构的方式:

struct Section {
    let name : String
    let items : [Portfolios]
}

struct Portfolios: Decodable {
    let code: String
    let maker: String
}

本质上,我需要帮助将复选标记应用于实际记录本身,而不仅仅是静态行。

标签: iosswiftuitableview

解决方案


最有效的方法是将isSelected信息添加到数据模型 ( Portfolios)

struct Portfolios : Decodable {
    var isSelected = false

    // other members 
}

您还可以添加CodingKeys以排除isSelected被解码。


cellForRowAt设置复选标记根据isSelected

let item = sections[indexPath.section].items[indexPath.row]
cell.accessoryType = item.isSelected ? .checkmark : .none

didSelectRowAt切换isSelected并重新加载行

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    sections[indexPath.section].items[indexPath.row].isSelected.toggle()
    tableView.reloadRows(at: [indexPath], with: .none)
}

推荐阅读