Tableview 配件加载不正确 [英] Tableview accessories don't load correctly
问题描述
我正在尝试在我的项目中收藏的报告旁边显示一个复选标记.我成功地将标题保存到 Core Data 并成功获取它们.我将它们加载到一个名为 favourite
的数组中.然后我与加载到单元格中的标题进行比较.
I am trying to display a checkmark next to favourited reports in my project. I save the title into Core Data successfully and fetch them successfully too. I load them into an array called favourite
. I then compare against the title loaded into the cell.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
guard let cell = tableView.dequeueReusableCell(withIdentifier: "CellClass") as? CellClass else { return UITableViewCell()}
cell.titleLbl.text = objArray[indexPath.section].sectionObj?[indexPath.row].title ?? "no title"
cell.descLbl.text = objArray[indexPath.section].sectionObj?[indexPath.row].authors ?? "no authors"
if (self.favourite.count > 0)
{
for i in 0...self.favourite.count - 1
{
if (objArray[indexPath.section].sectionObj?[indexPath.row].title == favourite[i].title!)
{
cell.accessoryType = .checkmark
}
}
}
return cell
}
目前,我在 Core Data 中只有一条数据,所以应该显示一个复选标记,但似乎我的表格视图中每 10 个单元格有一个递归模式.
Currently, I only have one piece of data in Core Data so one checkmark should be shown but it seems there is a recursive pattern of every 10 cells in my table view.
推荐答案
单元格得到重用.每当您有条件地设置单元格的属性时,您需要在其他情况下重置该属性.
Cells get reused. Whenever you conditionally set a property of a cell, you need to reset that property in other cases.
最简单的解决方案是在循环之前(以及在 if
之前)将 accessoryType
设置为 .none
.
The simplest solution is to set the accessoryType
to .none
before the loop (and before the if
).
我也建议稍微优化一下标题.您在这段代码中多次调用 objArray[indexPath.section].sectionObj?[indexPath.row].title
.做一次.
I also suggest optimizing the title a bit. You call objArray[indexPath.section].sectionObj?[indexPath.row].title
many times in this code. Do it once.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CellClass") as! CellClass
let title = objArray[indexPath.section].sectionObj?[indexPath.row].title ?? "no title"
cell.titleLbl.text = title
cell.descLbl.text = objArray[indexPath.section].sectionObj?[indexPath.row].authors ?? "no authors"
cell.accessoryType = .none
for favorite in self.favourite {
if title == favourite.title {
cell.accessoryType = .checkmark
break // no need to keep looking
}
}
return cell
}
我还展示了许多其他代码清理.
I've shown lots of other code cleanup as well.
这篇关于Tableview 配件加载不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!