解释:
我有一个从 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
}
本质上,我需要帮助将复选标记应用于实际记录本身,而不仅仅是静态行。
最有效的方法是添加isSelected
数据模型的信息(Portfolios
)
struct Portfolios : Decodable {
var isSelected = false
// other members
}
您还可以添加CodingKeys
排除isSelected
免于被解码。
In cellForRowAt
根据设置复选标记isSelected
let item = sections[indexPath.section].items[indexPath.row]
cell.accessoryType = item.isSelected ? .checkmark : .none
In didSelectRowAt
toggle isSelected
并重新加载该行
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
sections[indexPath.section].items[indexPath.row].isSelected.toggle()
tableView.reloadRows(at: [indexPath], with: .none)
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)