swift - 使用复选标记附件发出选择行
问题描述
我有一个从 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
}
是否也可以自动选择复选标记行?
解决方案
将结构成员声明为变量
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)
}
如果您负责后端,请发送marked
as Bool
,Int
非常麻烦。
推荐阅读
- java - 获取所有类参数及其名称?
- java - @Column 注释还不足以让 JPA 将一个驼峰式 Java 属性映射到数据库上的一个蛇形列吗?
- android-studio - 安装 android studio 时出现 Stacktrace.txt 错误
- filemaker - Filemaker Pro 18 从所有表中删除所有记录
- java - 无法弄清楚如何访问由 swagger 自动生成的 jaxrs 服务器中的请求标头
- flutter - OAuth2:注销后没有登录对话框,直接登录最后一个用户
- android - 在我的 Android 应用中的活动之间切换后,如何切换回上一个片段?
- python - 如何找到一个点在特定距离内的所有相邻点?
- django - 是否可以在没有 kwargs 的情况下在 django 中定义 success_url
- c# - 事件和代表的对立面?