Unable to set background color of UITableViewCell in IB

I created a group of cells that I reuse as a table. All these cells have different UILabel inside them, and some UIImageView (nothing covers the full cell).

Setting the background color in IB does not affect (always white or transparent, cannot say which one). But if I press Command-R (simulate an interface), the cell has the correct background color in the simulator.

I tried setting it to tableView:cellForRowAtIndexPath: but it does not work as I thought.

This is the trick:

 cell.contentView.backgroundColor = [UIColor redColor]; 

but they do not work (even if I set cell.contentView.backgroundColor to clearColor ):

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

I set all layout / font / background elements to IB. Any idea why this is not working in this case?

Why do I need to change the contentView backgroundColor and not backgroundView ?

This seems to be a common problem. Can someone please point me in the right direction (finally) to understand how the background colors are processed in the table view cell.

+30
ios iphone cocoa-touch uitableview interface-builder
Nov 10 2018-10-10T00:
source share
3 answers

It’s simpler there: when you create a UITableViewCell in Interface Builder, just drag and drop an additional UIView so that it covers the entire UITableViewCell that you create in IB. Place additional user interface elements on top of this optional UIView . You can install this optional UIView into any background you like.

There are several answers in StackOverflow that suggest changing the background color of your UITableViewCell with a line of code like this:

 cell.contentView.backgroundColor = [UIColor redColor]; 

If you add a shadow to a cell by slightly contentView flag, you may find that this row changes the background color of your cell and the color of your shadow region.

+1
Mar 27 '13 at 2:02
source share

To change the background color of a cell, you must do this in the willDisplayCell:forRowAtIndexPath: method. This is mentioned in the UITableViewCell documentation at the bottom of the overview. So you need to:

 - (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath { cell.backgroundColor = [UIColor redColor]; } 

ContentView is just the recommended subview for placing custom controls so that the cell is properly planned when editing the table.

+53
Nov 10 '10 at 3:11
source share

I found this Cocoa with love articles really useful as it looks at a fully customized table view and how to do it.

+1
Nov 10 '10 at 4:54
source share



All Articles