Swift Tableview配件don';不能正确加载

Swift Tableview配件don';不能正确加载,swift,uitableview,Swift,Uitableview,我试图在我的项目中最喜欢的报告旁边显示一个复选标记。我成功地将标题保存到核心数据中,并成功地获取它们。我将它们加载到一个名为favorite的数组中。然后,我将其与加载到单元格中的标题进行比较 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = tableView.dequeueReusableCell(wi

我试图在我的项目中最喜欢的报告旁边显示一个复选标记。我成功地将标题保存到核心数据中,并成功地获取它们。我将它们加载到一个名为
favorite
的数组中。然后,我将其与加载到单元格中的标题进行比较

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
}

目前,我的核心数据中只有一条数据,因此应该显示一个复选标记,但在我的表视图中,似乎每10个单元格就有一个递归模式。

单元格得到重用。无论何时有条件地设置单元格的属性,在其他情况下都需要重置该属性

最简单的解决方案是将
accessoryType
设置为
.none
在循环之前(如果
之前)

我还建议稍微优化一下标题。在此代码中多次调用
objArray[indexath.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
}

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

谢谢您的评论!这真的很有帮助!