Pablo Duque
Pablo Duque

Reputation: 383

UITableView changing things of some cells in Swift

I have a UITableView with a custom UITalbeCellView. Every cell has a title a body and a date. When I fetch the data some of the titles must be red so there is a Bool that is set to true for those cells which title has to be red.

The first time the data is fetched it looks fine, but as you scroll up and down a few times all of the titles end up being red.

Im using an array of structures to store the data and on the cellForRowAtIndexPath there is an if and if the boolean in that position of the array is true I change the color to red:

let cell = tableView.dequeueReusableCellWithIdentifier("CommentsRowTVC", forIndexPath: indexPath) as! CommentsRowTVC
let single_comment = self.AOS[indexPath.row]

cell.titulo_comentario?.text = single_comment.titulo_comment
if single_comment.flag == true {
    cell.titulo_comentario.textColor = UIColor.redColor()
}

Im gessing it reuses Views or something like that. Does this have any easy fix? Or do I have to implement my own TableView to prevent this from happening? Im also thinking the method dequeueReusableCellWithIdentifier might be the one causing my problem... but Im new on swift and cant think of any replacement for that.

It is happening similar thing on buttons there are on the cells, when you click a button from a cell it changes its color and disables it, but just the one on that cell. However when clicking on a cell, buttons from other cells are also suffering those changes.

Upvotes: 0

Views: 2484

Answers (1)

luk2302
luk2302

Reputation: 57124

Since cells get reused you end up with cells that were previously red because they hadsingle_comment.flag == true and are now used for another row where there actually is single_comment.flag == false. You have to reset the color in the else branch again:

if single_comment.flag == true {
    cell.titulo_comentario.textColor = UIColor.redColor()
} else {
    cell.titulo_comentario.textColor = UIColor.whiteColor()
}

UITableViews reuse their cells, meaning that you will get cells inside your cellForRowAtIndexPath which have previously been used before, maybe have have set the textColor to red. Your job is it now to revert the color of the text to its original state.

In general whatever change you make inside the if-branch of cell-customization has to be undone in the else-branch. If you remove a label in the if, add it in the else.

Upvotes: 4

Related Questions