I want to achieve the effect where one cell of the table view will have blue background, the next one will have white, the next one will have blue again, and then white and
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.
Add this method to your table view delegate:
#pragma mark UITableViewDelegate
- (void)tableView: (UITableView*)tableView
willDisplayCell: (UITableViewCell*)cell
forRowAtIndexPath: (NSIndexPath*)indexPath
{
cell.backgroundColor = indexPath.row % 2
? [UIColor colorWithRed: 0.0 green: 0.0 blue: 1.0 alpha: 1.0]
: [UIColor whiteColor];
cell.textLabel.backgroundColor = [UIColor clearColor];
cell.detailTextLabel.backgroundColor = [UIColor clearColor];
}
All you need to do is add the following code in your table's view controller implementation file.
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
if (indexPath.row%2 == 0) {
UIColor *altCellColor = [UIColor blackColor];
cell.backgroundColor = altCellColor;
}}
It's then as simple as adding and changing the modulus values.
You have to set the background color of the cell's content view
cell.contentView.backgroundColor = [UIColor colorWithRed...]
This will set the background of the whole cell.
To do this for alternate cells, use the indexPath.row
and %
by 2.
When using the default table cell setting the following two properties will color both the cell's background and the background color of it's label, avoiding the need to create a custom label as a subview of the cell's contentView.
cell.textLabel.backgroundColor = [UIColor redColor];
cell.contentView.backgroundColor = [UIColor redColor];
UIView *bg = [[UIView alloc] initWithFrame:cell.frame];
bg.backgroundColor = [UIColor colorWithRed:175.0/255.0 green:220.0/255.0 blue:186.0/255.0 alpha:1];
cell.backgroundView = bg;
[bg release];