Search code examples
iosobjective-cuitableviewcocoa-touchcell

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


Solution

  • 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]];