views:

107

answers:

2

I have a full list that populates a UITable. This I want to background the one of the cells with a different color and it works initially, but for some reason when I start scrolling the table up and down, it starts drawing more cells with the green background.

Please note that there is ALWAYS one detailCell.detailTimeLabel.text that's equal to currentTime.

The code I have is:

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

... SOME MORE CODE HERE ...

        if ([detailCell.detailTimeLabel.text isEqualToString:currentTime]) {  
            UIView* backgroundView = [[[UIView alloc] initWithFrame:CGRectZero] autorelease];
            backgroundView.backgroundColor = [UIColor greenColor];
            detailCell.backgroundView = backgroundView;
            for (UIView* view in detailCell.contentView.subviews) 
            {
                view.backgroundColor = [UIColor clearColor];
            } 
        }   
    }

Which can be the problem?

+2  A: 

Your trying to store data in a tableviewcell. You can't do this because the cells are constantly reused. The background you see repeated occurs because its the same cell being displayed over and over again with different text.

When you dequeue the cell, you need to reset it to blank and wipe out all the previous data. Then you should set the background color only if the data you are putting into the cell has the current time.

As a general rule, you should never refer to data in the cells. If you need to know what is in a particular cell, look at the data at the indexpath within the datamodel itself.

TechZen
A: 

hey same problem here...any help please..

This is my code:

  • (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"MainPageCellView"; MainPageTableCellView *cell = (MainPageTableCellView *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil) {
    [[NSBundle mainBundle] loadNibNamed:@"MainPageTableCellView" owner:self options:nil];
    cell = mainPageTableCell; }

    [cell setNameText:[namesArray objectAtIndex:indexPath.row]]; [cell setPositionText:[positionArray objectAtIndex:indexPath.row]]; [cell setCompanyNameText:[companyNameArray objectAtIndex:indexPath.row]]; [cell setDistanceText:[distArray objectAtIndex:indexPath.row]]; [cell setImageViewImage:[imagesArray objectAtIndex:indexPath.row]];

    UIImage *halo = [UIImage imageNamed:@"h1.png"]; UIImageView *haloV = [[UIImageView alloc] initWithImage:halo];

    if(indexPath.row == 0) [cell addSubview: haloV]; else if(indexPath.row ==2) [cell addSubview: haloV]; else if(indexPath.row ==3) [cell addSubview: haloV];

    return cell;

}

mano