Ruben Martinez Jr. Ruben Martinez Jr. - 1 year ago 64
iOS Question

cellForRowAtIndexPath Property Change Changes Multiple Cells

Disclaimer: I'm on iOS 8, so there's a chance this is a bug.

I'm attempting to programmatically edit the backgroundColor of a cell at a particular IndexPath in a UITableView after a particular event. I use the following code:

UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
cell.backgroundColor = [UIColor colorWithRed:1 green:0.84 blue:0 alpha:1];

While this works well, as soon as I scroll, I see other cell(s) with the changed background color. I think it has something to do with the following code in my
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

static NSString *simpleTableIdentifier = @"SimpleTableCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];

I suspect since all cells are generated with this identifier, somehow the properties are getting confused (though the style doesn't then apply to everything, only random cells, so that's points against this theory). Thanks for the help!

Answer Source

You need to change the background for all cells.

if (/* some condition for special background color */) {
    cell.backgroundColor = ... // special background color
} else {
    cell.backgroundColor = ... // normal background color

This avoid the reuse issue. You must follow this pattern for any cell attribute you wish to set differently for certain cells.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download