Hello,
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 so on... could you let me know how can I do that?
Thanks.
Hello,
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 so on... could you let me know how can I do that?
Thanks.
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.
The cell.contentView.backgroundColor = [UIColor colorWithRed...]
method in lostInTransit's answer works, as long as you do not use the built-in label of a UITableViewCell.
I found that if you use the built-in label, e.g. by setting cell.text
, you end up with a opaque white block under the label and only the two ends of the cell show your desired color.
I found no way to edit the built-in label so it is non-opaque (you can access it via UILabel* cellLabel = [cell.contentView.subviews objectAtIndex:0]
).
I solved the problem by adding my own custom UILabel
. Like this:
UILabel* cellLabel = [[[UILabel alloc] initWithFrame:cell.frame] autorelease];
cellLabel.text = @"Test with non-opaque label";
cellLabel.backgroundColor = [UIColor clearColor];
cellLabel.opaque = NO;
[cell.contentView addSubview:cellLabel];
cell.contentView.backgroundColor = [UIColor darkGrayColor];
This code is a slightly more clean solution for the case where you are using the built-in text label and don't want the white background color of the text label obscuring the background color. This also fixes the issue of violating the rounded corners of a grouped style of table view (which happens when you use cell.contentView.backgroundColor instead of cell.backgroundColor) :
UITableViewCell *cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
cell.backgroundColor = [UIColor redColor];
cell.textLabel.backgroundColor = [UIColor clearColor]; //transparent background
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];
}