gpt4 book ai didi

swift - Tableview 附件无法正确加载

转载 作者:行者123 更新时间:2023-11-30 10:53:02 25 4
gpt4 key购买 nike

我正在尝试在项目中收藏的报告旁边显示复选标记。我成功地将标题保存到核心数据中并成功获取它们。我将它们加载到名为 favourite 的数组中。然后我与加载到单元格中的标题进行比较。

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 中只有一项数据,因此应该显示一个复选标记,但我的表格 View 中似乎每 10 个单元格都有一种递归模式。

最佳答案

细胞被重复使用。每当您有条件地设置单元格的属性时,在其他情况下都需要重置该属性。

最简单的解决方案是设置 accessoryType.none在循环之前(以及 if 之前)。

我还建议稍微优化一下标题。您调用objArray[indexPath.section].sectionObj?[indexPath.row].title这段代码中多次出现。做一次。

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
}

我还展示了许多其他代码清理。

关于swift - Tableview 附件无法正确加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54263852/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com