[iOS] Self Sizing Cells & Dynamic Table Content Height

Self Sizing Cells was introduced in iOS 8. Starting from iOS 8, we can have dynamic cell height on rows in UITableView. The cell height would be determined based on the cell content.

To apply Self Sizing Cells:

  • Define auto layout constraints in the UITableView cell
  • Specify the tableview.estimatedRowHeight to a value that is most fit
  • Set the tableview.rowHeight to UITableViewAutomaticDimension
tableView.estimatedRowHeight = 160
tableView.rowHeight = UITableViewAutomaticDimension

 

Sometimes you may place the UITableView inside a UIScrollView, and specify the height of the UITableView based on its cells’ content.

To achieve dynamic height on UITableView:

  • Create and bind height constraint for your UITableView
  • Reload the tableview after the data is ready
  • Specify a max on height constraint (It won’t work without this trick)
  • Call layoutIfNeeded after that (It won’t work without this trick)
  • Finally set the height constraint to content size height
heightConstraint.constant = 1000000
tableView.layoutIfNeeded()
heightConstraint.constant = tableView.contentSize.height

Although UICollectionView does not have Self Sizing Cells, dynamic height is still applicable.

heightConstraint.constant = collectionView.collectionViewLayout.collectionViewContentSize().height

Reference: