Calculate Dynamic Table View Cell Height

Duc Ngo
2 min readJan 25, 2016

To display a table view with dynamic cell height, almost people would implement delegate heightForRowAtIndexPath with several conditions inside, the complexity will based on how much complexity the cell content is.

Here is a sample for what dynamic cell height is:

If you’re using Auto layout, there is a simpler way to do this without any calculating stuff, so you can also forget away heightForRowAtIndexPath delegate, just let Auto layout do its job.

Well, the essential of the trick are just three things:

  1. Set needed auto layout params on cell content.
  2. Enable UITableViewAutomaticDimension on tableview cell height.
  3. Give some pre-estimation number for tableview (for optimizing scrolling speed).

Set needed auto layout params on cell content

Just remember the rule is all items on table view cell need to be pinned on top, bottom,leadingand trailing edges from parent view. For example if your table view cell have two labels: brandNameLabel & brandAddressLabel, so the layout for those label would be:

for brandNameLabel:

for brandAddressLabel:

Enable UITableViewAutomaticDimension on tableview cell height

We just simple enable it by this code

mTableView.rowHeight = UITableViewAutomaticDimension

Give some pre-estimation number for tableview

Give directly the custom cell height you set on Interface Builder, this is optional step meant you can ignore it, but as I said, this number is used for auto layout calculating stuff when scrolling table view, to make it more smoothly

// this number is custom cell height on IB

mTableView.estimatedRowHeight = 120

or can implement this delegate for custom index path

This will make your life simple.

That’s is!

--

--