Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why does setting a UITableViewCell's color work in "willDisplayCell" but not in "cellForRowAtIndexPath"?

why does setting a UITableViewCell's color work in willDisplayCell but not in cellForRowAtIndexPath?

Notes:

  1. I'm using this code to set the background color of a cell: [cell setBackgroundColor:[UIColor yellowColor]];
  2. works when I put it in the method - (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
  3. does NOT work if I put in in - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
like image 850
Greg Avatar asked Oct 17 '11 23:10

Greg


1 Answers

The doco for UITableViewCell states that you need to do it in willDisplayCell: (excerpt from the UITableViewCell class reference below). I suspect that because table cells have a content view and various other components that seem to be 'managed' by UIKit, that its doing its own thing with the background color after its set in cellForRowAtIndexPath. You can also use the 'backgroundView' property of a table view cell to control its background.

documentation excerpt:

Note: If you want to change the background color of a cell (by setting the background color of a cell via the backgroundColor property declared by UIView) you must do it in the tableView:willDisplayCell:forRowAtIndexPath: method of the delegate and not in tableView:cellForRowAtIndexPath: of the data source. Changes to the background colors of cells in a group-style table view has an effect in iOS 3.0 that is different than previous versions of the operating system. It now affects the area inside the rounded rectangle instead of the area outside of it.

like image 156
gamozzii Avatar answered Sep 30 '22 13:09

gamozzii