Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Styling UITableViewCells with gradient backgrounds

I work for Tumblr, and while I didn't write the iPhone app (he did), I have the source and can tell you how it's done.

In -tableView:cellForRowAtIndexPath:

cell.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"postCellBackground.png"]];
cell.selectedBackgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"postCellBackgroundSelected.png"]];

Pretty simple, really: PNG images in a UIImageView as the cell's background views.

The two images are 1x61 vertical gradients that UIKit automatically stretches horizontally to fit the width of the cell.


As of iPhone SDK 3.0, there's a much simpler solution that relies on the new CAGradientLayer and doesn't require subclassing or images.


Marco's answer works great for plain table view cells and for grouped table view cells that are located in the middle of the table view, but if you try to set a background view for the first/last cell in a grouped table then it will break the rounded corners. To fix it you can set cell background color to a UIColor colorWithPatternImage, e.g:

cell.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"Gradient.png"]];