How to Make Custom Drawn Gradient Backgrounds in a Grouped UITableView with Core Graphics

2 minute read

In iPhone app design, it is important to find a balance between customization and familiarity. Many times, subtle differences are all you need to make yourself stand out from the crowd. While doing the Ambiance 3.0 redesign, I wanted something to make my list of content a little different than all the other cookie cutter table views out there.

A great place to start is to implement your own background and use a clear table view background. Many apps are now doing this and it is come to be expected from a grouped UITableView that is done with a little love. Another way to spruce up these tables is to add a custom background color. Since 3.0, this has been as easy as setting the cells backgroundColor property. I implemented both of these and it wasn't enough for me. It still looked like so many apps out there. I thought about putting a gradient view as the background, only to find that setting a grouped UITableViewCell's background ignored the nice rounded corners of the cell. Almost giving up, I googled around to see if anybody else has done it and shared some code.

This was a great resource as it helped me in the right direction — Core Graphics. It was meant as a way to customize the background of a cell before the 3.0 sdk came out, but I used it as a basis for my code to draw a gradient! It needed tweaking and optimization, but after a little bit of hacking away at it, I was able to get it to work nicely. I present to you the UACellBackgroundView.

To use the UACellBackgroundView, simply add the .h and .m files to your project, then use it as the cell background view.

.h file
.m file

Whenever you want to use it, just set the cell's backgroundView to be the UACellBackgroundView in your own UITableViewCell Subclass's initWithStyle method. Then, when you have your data and are creating cells, simply set the position of the cell by calling setPosition, of just call the line directly if you don't want to subclass the UITableViewCell. The position is important as it lets the cell know to draw itself correctly depending on whether or not the cell is first, last, in the middle, or a single cell.

Hope this helps you in your quest for a better app. If you want to use it, you will have to set your cell labels and elements to have a clear background, so hopefully you have a fast drawing method and have optimized your table view cells to do minimum work during scrolling.

Was this page helpful for you? Buy me a slice of πŸ• to say thanks!

Comments