Setting background color of a table view cell on iPhone
Solution 1:
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];
}
Solution 2:
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.
Solution 3:
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.
Solution 4:
please add the following code in the cellForRowAtIndexPath
if (indexPath.row % 2 == 0){
cell.backgroundColor =[UIColor blueColor];
} else {
cell.backgroundColor =[UIColor whiteColor];
}
i think this will help you