Rubén T.F.
Rubén T.F.

Reputation: 134

Color problems with custom UITableViewCell

I'm developing some app with custom UITableViewCells. I've one nib for the cell and I use only a cell identifier.

In cellForRowAtIndexPath I've some code like this:

_spot.text = [NSString stringWithFormat:@"%d.", [forecastRow.position intValue]];
if([[forecastRow prob1] floatValue] > 0.5){
    _spot.textColor = [UIColor redColor];
}

where _spot is an UBOutlet for an UILabel. The fact is that the number is shown correctly, and the color is firstly assigned to the proper cells. But, when I scroll, numbers keep ok, but the color red is assigned randomly to _spot label on other cells not passing the if() all over the table.

What's happening? Why the text is correct, but not the color? Why this messes up only when scrolling? I think the solution is not using several identifiers and nibs for such a little task (change a UILabel color), as I need to assign more than one different color to the row's labels, based on complex conditions.

Upvotes: 0

Views: 72

Answers (1)

FreaknBigPanda
FreaknBigPanda

Reputation: 1127

It looks like you are updating the text with every request for a new cell but not the color. What is happening is cell re-use is causing the cells the be reused when you scroll and is not updating the color properly. Change your code to something like:

_spot.text = [NSString stringWithFormat:@"%d.", [forecastRow.position intValue]];
if([[forecastRow prob1] floatValue] > 0.5){
    _spot.textColor = [UIColor redColor];
} else
{
    _spot.textColor = [UIColor (original color)];
}

This will force the color update on each request.

Upvotes: 3

Related Questions