Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting background color of a table view cell on iPhone

Tags:

iphone

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.

like image 341
ebaccount Avatar asked May 22 '09 21:05

ebaccount


People also ask

Can we change the background color of a single cell in a table?

Background Color for Table Cell. You can also change the background color of an individual table cell. To do this, simply apply the styles against the <td> tag of the table cell in question.


2 Answers

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]; } 
like image 136
jessecurry Avatar answered Oct 14 '22 00:10

jessecurry


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.

like image 29
lostInTransit Avatar answered Oct 14 '22 00:10

lostInTransit