13

I'm trying to set the label backgroundColor of my UITableViewCells and it does absolutely nothing at all. I wonder if there's another way of doing this, so I'm asking!

I tried this:

    cell.textLabel.backgroundColor = [UIColor redColor];
cell.backgroundColor = [UIColor redColor];

And it doesn't work, anything else?

Thanks!

Tommy B.
  • 3,591
  • 14
  • 61
  • 105

2 Answers2

46

I assume you are trying this in cellForRowAtIndexPath.

According to the UITableViewCell class reference:

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.

So do this:

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    cell.backgroundColor = [UIColor redColor]; //must do here in willDisplayCell
    cell.textLabel.backgroundColor = [UIColor redColor]; //must do here in willDisplayCell
    cell.textLabel.textColor = [UIColor yellowColor]; //can do here OR in cellForRowAtIndexPath
}

If you need finer control over the cell display, an easy way is to design it in IB and load it from the nib in cellForRowAtIndexPath. See the "Loading Custom Table-View Cells From Nib Files" section on this page in the Table View Programming Guide.

0

Update for IOS 9.3. This actually works fine in cellForRowAtIndexPath using IOS 9.3. Also Note: To change the color of the entire cell use:

cell.contentView.backgroundColor = [UIColor redColor];

John
  • 538
  • 4
  • 18