Tableview accessories don't load correctly

Viewed 43

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
}

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.

1 Answers

Cells get reused. Whenever you conditionally set a property of a cell, you need to reset that property in other cases.

The simplest solution is to set the accessoryType to .none before the loop (and before the if).

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.

Related