Reputation: 17072
To make my UITableView looks better, I need to change the background color of each cell alternatively.
As I did not manage to change the background color directly, I've added a UILabel in the background of the cell and then do the following (in the cellForRowAtIndexPath method):
// Set cell color
if(indexPath.row % 2 == 0){
UIView *bckView = (UIView *)[cell viewWithTag:100];
bckView.backgroundColor = [UIColor colorWithRed:226.0/255.0 green:243.0/255.0 blue:1.0 alpha:1.0];
}
When the list is displayed for the first time it looks good (first cell is light blue, second is white, third is light blue...). But... when I play and move several times the list up and done the background color of the cells got mixed. I'm pretty sure this is linked to the fact the cell are reused but I cannot figure out how to solve this. Any idea ?
Upvotes: 3
Views: 2091
Reputation: 11084
You will need an else to go along with your if in order to set the color the other way, otherwise, eventually, all of your cells will end up the same color.
Also, if you only have that method inside if(!cell) or if(cell == nil) code block, it won't get called when showing a dequeued cell. So, you need to make sure its in a block that gets called every time.
Upvotes: 2
Reputation: 5151
Add an else part to the if statement where you set the background color to the other color.
Upvotes: 3
Reputation: 31016
You need an else
to set the other color since you can't predict what color you set it last time for a reused cell.
Upvotes: 9