how to set different background colors for cells in a UITableView (specifically rainbow color for seven cells)
If you want to set cell color based on some state in the actual cell data object, then this is another approach:
If you add this method to your table view delegate:
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
cell.backgroundColor = cell.contentView.backgroundColor;
}
Then in your cellForRowAtIndexPath method you can do:
if (myCellDataObject.hasSomeStateThatMeansItShouldShowAsBlue) {
cell.contentView.backgroundColor = [UIColor blueColor];
}
This saves having to retrieve your data objects again in the willDisplayCell method.
Try this
cell.backgroundVIew.backgroundColor = [UIColor orangeColor];
Pretty sure UITableViewCell is a subclass of UIView, so:
cell.backgroundColor = [UIColor blueColor];
For awful rainbow colors, here is an example:
static NSArray *colors = [NSArray arrayWithObjects:[UIColor redColor], [UIColor yellowColor], etc..., nil];
cell.backgroundColor = [colors objectAtIndex:indexPath.row];
Do not forget to set background color of your tableView to clearColor. Otherwise the clearColor of cell will not be displayed as the background color of tableView will be whiteColor by default. And even when the cell color turns to clearColor whiteColor will be displayed because the tableView background color is still whiteColor. Remenber.
If you've subclassed UITableViewCell
, you can reliably set self.backgroundColor
in -layoutSubviews
. At least in my experience, this works in the odd cases where tableView:willDisplayCell:forRowAtIndexPath: does not.
Set the backgroundColor
property:
cell.backgroundColor = [UIColor redColor];
Note that the backgroundColor must be set in the tableView:willDisplayCell:forRowAtIndexPath:
method (from UITableViewCell 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. 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.
Use the indexPath parameter to achieve the rainbow effect.