UITableViewCells with dynamic height based upon Auto Layout constraints is actually an easy job once you figured out what's required to make this work. This blog post will briefly explain how to create a
UITableViewCell in which height is calculated dynamically by the
UITableView depending on what content it contains.
Step 1: Create the cell
This example assumes your
UITableViewCell contains just a label with a random amount of text that should word-wrap in case it gets too long to be displayed in one line.
Given you're using a XIB or Storyboard file for your
UITableViewCell, your setup might look similar to the following. Only a few Auto Layout constraints are required for this simple setup.
UILabel has a constraint for its leading, top and bottom space relative to the superview (the cell's content view).
Make sure to set is the label's
preferredMaxLayoutWidth property. It was introduced in iOS 6.0, so this solution should also work with iOS versions up to 8.0.
preferredMaxLayoutWidth will tell iOS a) to set a preferred maximum width for your label and b) when it should break your content so the label will look according to your needs.
Make sure to set up everything else that is required to have your label line-breaking by setting its
numberOfLines to 0 and its
lineBreakMode to word-wrap.
Step 2: Implement the UITableViewDelegate
UITableViewDelegate itself needs to take care of calculating the correct required height for each cell based upon its content. For this, we'll use the following implementation in this example:
The interesting part happens in the
tableView:heightForRowAtIndexPath: implementation: We instantiate a reusable
UITableViewCell, set it up and calculate its height with the help of
systemLayoutSizeFittingSize:. The result looks like this:
Download the sample code
Feel free to check out the sample code used in this blog post on GitHub and improve or reuse it for your own purpose.
Please let me know your thoughts and comments by pinging me on Twitter.
Disclaimer: This article was first posted in my personal blog.