ML1426 ML1426 - 22 days ago 9
Objective-C Question

cellForRowAtIndexPath doing weird action at specific indexpath

I tried to change backgroundColor and textLabel of a cell at a specific indexPath.row on UITableViewCell. The problem is that, the textLabel changed at my indicated indexPath.row correctly. However when I scrolled the UITableView, some cells change background color not only on that indexPath.row, but also these unwilling other cells changed, which these cells are not at my required indexPath.row.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
UITableViewCell* aCell;
aCell = [tableView dequeueReusableCellWithIdentifier:@"myCell" forIndexPath:indexPath];
if (indexPath.row == 7) {
NSLog(@"enter this specific row");
aCell.textLabel.text = [cellArray objectAtIndex:indexPath.row];
[aCell setBackgroundColor:[UIColor lightGrayColor]];
return aCell;

I added a NSLog on indexPath.row match condition, the console only printout the text whenever indexPath.row equal desire. The weird thing is the UITableViewCell change background color without come into condition, as the printout did not work on this.
I assume the variable aCell did not work properly follow indexPath.
My question is how the [aCell setBackgroundColor:[UIColor lightGrayColor]]; work correctly by desired indexPath.row.

Some one could give me an advice. thanks a lot.

Answer Source

Think about how cells are reused in different rows. You have changed the color of this cell forever. So when it is reused in a different row, it still has the changed color.

The solution is to configure the cell both when this is row 7 and when this is not row 7.

if (indexPath.row == 7) {
    // ... light gray background
} else {
    // ... _not_ light gray background!