2

How do I fill the background color of a UITableViewCell? I tried this code but it didn't work.

cell.backgroundColor = [UIColor redColor];
Michael Petrotta
  • 59,888
  • 27
  • 145
  • 179
RAGOpoR
  • 8,118
  • 19
  • 64
  • 97
  • 1
    What doesn't work about it? Where are you putting that code? More info please! – Grant Paul Feb 22 '10 at 02:25
  • Is this a dupe of http://stackoverflow.com/questions/400965/how-to-customize-the-background-border-colors-of-a-grouped-table-view ? – Mike Akers Feb 22 '10 at 02:41
  • I don't think Se3fan should've gotten credit for an answer on a duplicate question. No offense St3fan. – Jann Feb 22 '10 at 05:57

3 Answers3

2

Try setting a backgroundView for UITableViewCell :

UIView *bgView = [[UIView alloc] init];
bgView.backgroundColor = [UIColor redColor];
cell.backgroundView = bgView;
// release object
[bgView release];

You can change the selection background view of UITableViewCell the same way.

cell.selectedBackgroundView = bgView;
syd
  • 71
  • 4
1

Take a look at the following snippet from the UITableViewCell documentation.

http://developer.apple.com/library/ios/#documentation/uikit/reference/UITableViewCell_Class/Reference/Reference.html

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.

That should solve your problem.

xmlhack
  • 61
  • 4
1

Setting the background color though UITableViewCell's backgroundColor property only works in a Grouped table view. So if your table view is in the Plain style then it won't work.

You can of course set the background color of the UITableView's contentView. But then you probably have to do some additional work as the other subview (text labels and accessory views) have their own idea of background colors.

Stefan Arentz
  • 34,311
  • 8
  • 67
  • 88