ios - 如何将 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
}
本质上,我需要帮助将复选标记应用于实际记录本身,而不仅仅是静态行。
解决方案
最有效的方法是将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)
}
推荐阅读
- bash - awk 模式范围 - 如何仅打印最后一个范围匹配
- java - JAVA:printwriter 打印奇怪的符号?
- c# - LINQ如何返回最后一个日期和第一个和最后一个计数之间的差异
- mysql - 如何在 MySql docker 映像中运行 Django 种子数据?
- c# - 如何通过 API 设置 webhook URL
- c - 在c中的预处理器时间内获取定义值
- bash - linux读取命令 - 什么未使用,丢弃?
- c++ - 将 std::string_view 返回到 const char *
- python - 如何定期对格子行的元素求和
- flutter - 如何在 Flutter 中的盒子装饰上的图像上添加不透明覆盖