Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create rows with alternating colors for a UITableView on iPhone?

i would to have alternate 2 colors of rows, like the first black, the second white, the third black, etc, etc...

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
cell = ((MainCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier]);
if (cell==nil) {

    NSArray *topLevelObjects=[[NSBundle mainBundle] loadNibNamed:@"MainCell"    owner:self options:nil];

    for (id currentObject in topLevelObjects){
        if ([currentObject isKindOfClass:[UITableViewCell class]]){
            if ((indexPath.row % 2)==0) {
                [cell.contentView setBackgroundColor:[UIColor purpleColor]];

            }else{
                [cell.contentView setBackgroundColor:[UIColor whiteColor]];

            }
            cell =  (MainCell *) currentObject;
            break;
        }
    }

}else {

    AsyncImageView* oldImage = (AsyncImageView*)
    [cell.contentView viewWithTag:999];
    [oldImage removeFromSuperview];
}return cell;

The problem is that when i do a rapid scroll, the background of cells become like the last 2 cell black, the first 2 cell white or something like this, but if i scroll slow works fine. I think the problem is the cache of reusableCell.

Any ideas?

TIA

like image 887
Mat Avatar asked Apr 02 '10 21:04

Mat


2 Answers

Cells get recycled (that is what you are doing when you dequeue them and check if it is nil). So instead of setting the background color when you create the cell, set it sometime after. So:

if( !cell ) {
  // create the cell and stuff
}
if( [indexPath row] % 2)
  [cell setBackgroundColor:[UIColor whiteColor]];
else
  [cell setBackgroundColor:[UIColor purpleColor]];
like image 55
Jason Coco Avatar answered Oct 20 '22 01:10

Jason Coco


What I believe is happening is that when you dequeue a reusable cell, you do not do so in a defined order. As it would happen, when you scroll slowly, cells become available one at a time, and dequeued to you, in order. When you scroll quickly, the order becomes undefined, as does the order in which they are dequeued. I believe this is why (in large part) apple designed the UITableView API to dequeue by identifier - so you could reuse different types of cells, such as those with different colors, easily. As such, I recommend modifying the code to have each cell color have its own identifier. (Furthermore, if possible have an outlet connecting this tableview datasource to the cell directly, or save it in an ivar after loading it once, and then copy it rather than cycling through high level objects)

like image 27
Jared Pochtar Avatar answered Oct 19 '22 23:10

Jared Pochtar