iOS – Customize Table View Cells

Ever wanted to have alternated colors on your table view cells? If so, you’ve probably done something inside of cellForRowAtIndexPath and applied a background color to your cell there.

Would you be surprised to know that’s completely wrong?  Yup.  Wrong.  WRONG WRONG WRONG.

I didn’t know this, but any styles applied to cells based on state or whatever should really be in willDisplayCell – NOT when you configure the cell itself!  Per Apple’s documentation for the Table View delegate –

“A table view sends this message to its delegate just before it uses cell to draw a row, thereby permitting the delegate to customize the cell object before it is displayed. This method gives the delegate a chance to override state-based properties set earlier by the table view, such as selection and background color. After the delegate returns, the table view sets only the alpha and frame properties, and then only when animating rows as they slide in or out.”

Keep this in mind especially if you’re using a NSFetchedResultsController with CoreData.  You’ll have to issue a [tableView reloadRowsAtIndexPaths:…] in your didChangeObject method.  For some reason, at least in iOS 4.3.3, the willDisplayCell isn’t firing with the default code Apple recommends when using a Fetched Results Controller.  Adding that reload does the trick.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s