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.
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.
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.
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.
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];
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With