Hi,
How can I set the background color of a cell in UITableView?
Thanks.
Hi,
How can I set the background color of a cell in UITableView?
Thanks.
Update
Apparently the existing UITableViewCell framework makes it very difficult to change the background color of a cell and have it work well through all its state changes (editing mode, etc.).
A solution has been posted at this SO question, and it's being billed on several forums as "the only solution approved by Apple engineers." It involves subclassing UITableViewCell and adding a custom view for the subclassed cell's backgroundView
property.
Original post - this solution doesn't work fully, but may still be useful in some situations
If you already have the UITableViewCell object, just alter its contentView
's backgroundColor
property.
If you need to create UITableViewCells with a custom background color, the process is a bit longer. First, you'll want to create a data source for your UITableView - this can be any object that implements the UITableViewDataSource
protocol.
In that object, you need to implement the tableView:cellForRowAtIndexPath:
method, which returns a UITableViewCell when given an NSIndexPath for the location of the cell within the table. When you create that cell, you'll want to change the backgroundColor
property of its contentView
.
Don't forget to set the dataSource
property of the UITableView to your data source object.
For more info, you can read these API docs:
tableView:cellForRowAtIndexPath
contentView
backgroundColor
dataSource
Note that registration as an Apple developer is required for all three of these links.
The backgroundView is all the way on the bottom. It's the one that shows the rounded corners and the edges. What you want is the contentView which is on top of the backgroundView. It covers the usually white area of the cell.
This works perfect for me: NSEnumerator enumerator = [cell.subviews objectEnumerator]; id anObject; while (anObject = [enumerator nextObject]) { if( [anObject isKindOfClass: [ UIView class] ] ) ((UIView)anObject).backgroundColor = [UIColor lightGrayColor]; }
The version I wrote will work in iPhone 3.0 or higher and fallback to a white background otherwise.
In your viewDidLoad
method of the UITableViewController
we add the following:
self.view.backgroundColor=[UIColor clearColor];
// Also consider adding this line below:
//self.tableView.separatorColor=[UIColor clearColor];
When you are creating your cells (in my code this is my tableView:cellForRowAtIndexPath:
) add the following code:
cell.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageNamed:@"code_bg.png"]];
float version = [[[UIDevice currentDevice] systemVersion] floatValue];
if (version >= 3.0)
{
[[cell textLabel] setBackgroundColor:[UIColor clearColor]];
}