Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set the background color of a cell in UITableView on iphone?

How can I set the background color of a cell in UITableView?

Thanks.

like image 217
ebaccount Avatar asked Dec 13 '22 04:12

ebaccount


1 Answers

I know this is an old post, but I am sure some people are still looking for help. You can use this to set the background color of an individiual cell, which works at first:

-(UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath {
     [cell setBackgroundColor:[UIColor lightGrayColor]];

However, once you start scrolling, the iphone will reuse cells, which jumbles different background colors (if you are trying to alternate them). You need to invoke the tableView:willDisplayCell:forRowAtIndexPath. This way, the background color gets set before the reuse identfier is loaded. You can do it like this:

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
     cell.backgroundColor = ([indexPath row]%2)?[UIColor lightGrayColor]:[UIColor whiteColor];
}

The last line is just a condensed if/else statement. Good luck!

like image 180
alexshafran Avatar answered May 22 '23 04:05

alexshafran