如何将tableview单元格附件应用于tableview记录 [英] How to apply tableview cell accessory to a tableview record
问题描述
说明:
我有一个从JSON填充的UITableView.表格视图的目的是让用户选择单个行记录,并在结果中显示选中标记附件.
I have a UITableView that is being populated from JSON. The purpose of the tableview is for the user to select individual row records and have the checkmark accessory appear as a result.
问题是,尽管我可以为选中的任何行显示复选标记,但复选标记将应用于该行,而不是记录本身.
The issue is that while I can get the checkmark to appear for whichever row is selected the checkmark is applied to the row, not the record itself.
例如,如果我在表视图中有两行并且选择了第一行,则会对其应用一个复选标记,但是在更新API以删除该行并重新加载tableView之后,第一行消失了,但复选标记为应用于第二条记录.
For example, if I have two rows in the tableview and I select the first row, a checkmark is applied to it, but after updating the API to remove the row and reloading the tableView the first-row disappears but the checkmark is applied to what was the second record.
这是我的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
}
本质上,我需要帮助将复选标记应用于实际记录本身,而不仅仅是静态行.
Essentially I need help applying the checkmark to the actual record itself not just the static row.
推荐答案
最有效的方法是将 isSelected
信息添加到数据模型( Portfolios
)>
The most efficient way is to add the isSelected
information to the data model (Portfolios
)
struct Portfolios : Decodable {
var isSelected = false
// other members
}
您还可以添加 CodingKeys
,以将 isSelected
从解码中排除.
You might add also CodingKeys
to exclude isSelected
from being decoded.
在 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)
}
这篇关于如何将tableview单元格附件应用于tableview记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!