fonnes
fonnes

Reputation: 509

Custom UITableViewCell showing incorrect values

I have a UITableViewController displaying custom cells with a few labels and a custom UIView. In the tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) method it seems that the colors are not being reset when the cells are reused (they appear completely random). How can I fix this?

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let historyEntry = allHistoryEntries[indexPath.section].histories![indexPath.row]

    let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! HistoryCell

    cell.dateLabel.text = "\(getDayFrom(date: (historyEntry.beginDate)!))"

    let highestBac = getHighestBac(history: historyEntry)
    cell.highestBacLabel.text = "Høyeste promille " + String(describing: Double(highestBac).roundTo(places: 2))

    cell.costLabel.text = String(describing: getNorwegianDayFrom(date: (historyEntry.beginDate!))) + " brukte du " + String(describing: calculateTotalCostBy(history: historyEntry)) + ",-"

    let goal = Double(AppDelegate.getUserData()?.goalPromille ?? 0.0)
    let red = UIColor(red: 193/255.0, green: 26/255.0, blue: 26/255.0, alpha: 1.0)
    let green = UIColor(red:26/255.0, green: 193/255.0, blue: 73/255.0, alpha: 1.0)

    let color = highestBac > goal ? red : green

    cell.highestBacLabel.textColor = color
    cell.circleView.ringColor = color

    return cell
}

Here is an image showing the colors. The expected behavior is that red OR green color should be used, not a combination.

UPDATE: It is only the ringColor showing the wrong color.

enter image description here

Upvotes: 3

Views: 1111

Answers (3)

Leandro P
Leandro P

Reputation: 213

if there is no default color, reset the color to clear with prepareForReuse(). This function must be inside your HistoryCell class

override func prepareForReuse() {
    super.prepareForReuse() 
    //Reset label to clear color
    self.highestBacLabel.textColor = UIColor.clear
}

Upvotes: 2

fonnes
fonnes

Reputation: 509

So the problem turned out to be a lack of calling setNeedsDisplay() in my CircleView class. Thanks William GP.

Upvotes: 1

creeperspeak
creeperspeak

Reputation: 5523

If you need to reset some value, such as textColor when a cell is being dequeued for reuse you can override the prepareForReuse method in the UITableViewCell subclass (HistoryCell) like so:

override func prepareForReuse() {
    super.prepareForReuse() 
    //Reset label color back to default green
    let green = UIColor(red:26/255.0, green: 193/255.0, blue: 73/255.0, alpha: 1.0)
    self.highestBacLabel.textColor = green
}

Upvotes: 0

Related Questions