Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing background color of a custom UITableViewCell cell in a plain styled UITableView

I am trying to change the background color of a custom UITableViewCell in a plain style UITableView.

I've read the other similar questions, and I in my delegate method:

- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath

I set cell.backgroundColor = [UIColor...]. The problem is this only works for a grouped style UITableView.

Note: The reason why I want to do this programmatically and not in my .xib file is because I want different background colors for different cells.

like image 216
Man of One Way Avatar asked Jul 08 '11 08:07

Man of One Way


People also ask

How do you change the background color of a Tableview cell?

For changing the background color of the table view cell, you should change the contentView. backgroundColor property of the cell. Now run the project to see the effect.

How can we use a reusable cell in UITableView?

For performance reasons, a table view's data source should generally reuse UITableViewCell objects when it assigns cells to rows in its tableView(_:cellForRowAt:) method. A table view maintains a queue or list of UITableViewCell objects that the data source has marked for reuse.


2 Answers

Maybe you can add cell.contentView.backgroundColor = [UIColor clearColor] before you set your color.

The reason is that the backgroundview is at the bottom. The contentview is at the top.

like image 102
Bonny Avatar answered Oct 29 '22 21:10

Bonny


Change the color in the following delegate method:

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (...){
        cell.backgroundColor = [UIColor blueColor];
    } else {
        cell.backgroundColor = [UIColor whiteColor];
    }
}
like image 44
Jim Huang Avatar answered Oct 29 '22 22:10

Jim Huang