Make your UITableViews stand out with alternating row colors

UITableViews are the foundation of many iOS apps. Although they are pretty powerful and flexible, they are also very bland in their default configuration.

A quick and easy way to add some style to your boring UITableViews is to add alternating row colors. This gives them some visual ‘pop’ and improves readibility. No fancy design skills required!

Here is a sample UITableView from 20 Rep Squats. It’s a little bit… monotonous.

iOS Simulator Screen shot 2013-01-12 6.51.28 PM

Let’s spice it up a bit. Open your UITableViewController’s .m file, and insert the following code:

-(void) tableView:(UITableView*)tableView willDisplayCell:(UITableViewCell*)cell forRowAtIndexPath:(NSIndexPath*)indexPath
{
    UIColor* color = indexPath.row % 2 == 0 ? [UIColor whiteColor] : [UIColor colorWithRed:0.95 green:0.95 blue:0.95 alpha:1.0];
    cell.backgroundColor = color;
}

All we are doing is specifying that even numbered rows will have a white background, and odd numbered rows will have a nice subtle light grey background. Of course, you’ll want to store your background colors in fields or constants, and not have to regenerate them with colorWithRed:geen:blue: every time, but that’s beside the point of this post.

The result looks like this:

iOS Simulator Screen shot 2013-01-12 6.51.01 PM

And there you have it – with only a few seconds of effort, you can take your UITableViews from blah to beautiful! Or blah to average, at the very least.

2 Comments

  1. Does this need to be called or is it called automatically? I am subclassing UITableViewController which I think automatically makes me the delegate, but the code isn’t effecting the table cells at all.

    Reply

    1. Okay you have to provide info for the two required methods in the tableview I put 9 for number of rows and 1 for number of sections and the code is working. I assumed youmcould just fire this up and run a quick test. Still quick just I missed some steps. Thanks for the code.

      Reply

Leave a Reply

Your email address will not be published. Required fields are marked *