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 which height is being calculated dynamically by the
UITableView depending on what content it contains.
Step 1: Create the cell
This example will assume your
UITableViewCell will contain just a label which can contain 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).
The very important value to set is the labels
The property has been introduced with iOS 6.0  therefore this solution might also work with iOS versions earlier than 8.0.
Setting it will tell iOS what the preferred maximum width for your label should be, and 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 as follows:
Download the sample code
Thank you for reading this publication. I do not allow comments on my website, but I appreciate your thoughts and notes via email.