How to customize the background color of a UITableViewCell? How to customize the background color of a UITableViewCell? ios ios

How to customize the background color of a UITableViewCell?


Here is the most efficient way I have come across to solve this problem, use the willDisplayCell delegate method (this takes care of the white color for the text label background as well when using cell.textLabel.text and/or cell.detailTextLabel.text):

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath { ... }

When this delegate method is called the color of the cell is controlled via the cell rather than the table view, as when you use:

- (UITableViewCell *) tableView: (UITableView *) tableView cellForRowAtIndexPath: (NSIndexPath *) indexPath { ... }

So within the body of the cell delegate method add the following code to alternate colors of cells or just use the function call to make all the cells of the table the same color.

if (indexPath.row % 2){    [cell setBackgroundColor:[UIColor colorWithRed:.8 green:.8 blue:1 alpha:1]];}else [cell setBackgroundColor:[UIColor clearColor]];

This solution worked well in my circumstance...


You need to set the backgroundColor of the cell's contentView to your color. If you use accessories (such as disclosure arrows, etc), they'll show up as white, so you may need to roll custom versions of those.


This is really simple, since OS 3.0 just set the background color of the cell in the willDisplayCell method.You must not set the color in the cellForRowAtIndexPath.

This works for both the plain and grouped style :

Code:

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

P.S: Here the documentation extract for willDisplayCell :

"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."

I've found this information in this post from colionel. Thank him!