Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cell.backgroundColor not responding if set at tableView:cellForRowAtIndexPath

I am trying to color certain table row with red so I tried adding

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
... init Code here
cell.backgroundColor = [UIColor redColor];
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}

The accessory Checkmark appears but not the red color.

I later found that by placing it in tableView:willDisplayCell it works. Is this by design? why is it ignoring the value I already set at the moment of initializing the cell?

like image 436
Ben Quan Avatar asked Jan 12 '12 01:01

Ben Quan


2 Answers

The look of the cell is customized in tableView:willDisplayCell. So, to answer your question, yes it is by design. Accessory views and subviews of the contentView of the cell need to be modified/assigned in cellForRowAtIndexPath.

From the documentation of tableView:willDisplayCell:forRowAtIndexPath: :

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.

like image 63
Ravi Avatar answered Nov 01 '22 14:11

Ravi


FYI, Ravi's answer is correct, but if you would like to simplify your implementation, you may also set the cell's contentView background color to achieve the same effect.

cell.contentView.backgroundColor = [UIColor redColor];

This is not the documented solution, but the following will work:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
... init Code here
    cell.contentView.backgroundColor = [UIColor redColor];
    cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
like image 21
BreadicalMD Avatar answered Nov 01 '22 13:11

BreadicalMD