views:

33

answers:

1

In the tableView:accessoryButtonTappedForRowWithIndexPath: selector, I want to update the backgroundColor of the cell.

I can get the UIViewTableCell using cellForRowAtIndexPath: but I'm not sure how I can update its background color. The code beliw doesn't seem to work.

    [_tableView beginUpdates];
    cell.backgroundColor = [UIColor grayColor];
    [_tableView endUpdates];

Any suggestions?

A: 

I would first try [cell setNeedsDisplay];.

Also beginUpdates and endUpdates is meant to be used when you are going to be inserted/deleting rows etc. so I don't think it's necessary here.

Background colors on cells is a tricky thing because the table view will do some magic behind the scenes to handle cell selection. To get reliable behaviour you need to set the cell's background color in this UITableViewDelegate method:

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell
forRowAtIndexPath:(NSIndexPath *)indexPath

A table view sends this message to its delegate just before it uses cell to draw a row, thereby permitting the delegate to customize the cell object before it is displayed. This method gives the delegate a chance to override state-based properties set earlier by the table view, such as selection and background color. After the delegate returns, the table view sets only the alpha and frame properties, and then only when animating rows as they slide in or out.

Mike Weller
the tableView:willDisplayCell:forRowAtIndexPath: is only invoked when the table is first loaded. If I want to change it when the accesoryURL is clicked, setting [tableView setNeedsLayout] doesn't cause this method to be invoked. Any idea how I can make that happen?
psychotik