TableViewCell background color is disabled when table view is scrolled

350 Views Asked by At

In my application, I have a tableView, I changed the background color of cell when it is selected, I wrote that code as

- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.backgroundColor = [UIColor whiteColor];
}

The problem is When I scrolled the tableView, the background color of cell is disabled, the white color is not visible means the background color effect is removed. The table view reused the cell when scrolled out so the cell background effect is removed. I know where I get the problem but I don't know how to handle this problem and keep the background color of selected cell as white even the table view is scrolled. Please tell me solution for this problem.

2

There are 2 best solutions below

2
On

The best way to change the background of selected rows would be to change the selectedBackgorundView when you create the cell. That way, you wouldn't need to handle didSelectRowAtIndexPath:

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"myCellId";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        UIView *v = [[UIView alloc] init];
        v.backgroundColor = [UIColor whiteColor];
        cell.selectedBackgroundView = v; // Set a white selected background view. 
    }
    // Set up the cell...
    cell.textLabel.text = @"foo";
    return cell;
}
2
On

This will not work, because cells get reused. So your backgroundColor will probably get overwritten as soon, as the cell gets reused.

You should use the cell backgroundView. Exactly as Pulkit wrote already.