Tableview附件无法正确加载

时间:2018-11-12 01:24:32

标签: swift uitableview

我正在尝试在我的项目中最喜欢的报告旁边显示一个对勾。我成功将标题保存到Core Data中,并且也成功获取了它们。我将它们加载到名为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中只有一个数据,因此应该显示一个选中标记,但是在我的表格视图中似乎每10个单元格都有一个递归模式。

1 个答案:

答案 0 :(得分:2)

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

最简单的解决方案是在循环之前(以及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
}

我还展示了许多其他代码清除功能。