4

I am in a situation where I want to have UITableViewCells which have variable number of subviews depending on the data. Obviously this would lead to dynamic height of each cell. I researched and found a very nice post at Using Auto Layout in UITableView for dynamic cell layouts & variable row heights. The Sample project at github shows how to calculate the height of cell with fixed number of subviews i.e two UILabels, where one label is multi-line. I understand that but in my case these labels can vary in number.

My first approach is that I can add a UIView in the Cell's contentView and then add all the UILabels in this view when they are available. (Probably when calculating heightForRowAtIndexPath). Then in UpdateConstraints of subclass of tableViewCell I add all the required constraints, and hoping that the UIView will expand to take the combined height of all the UILabels in it. But this seems to be doing it. I know that UIView doesn't have intrinsicContentSize calculated. But how do we make sure now that it takes the size of it's subview.

Second approach I tried is directly adding the UILabels in the cell's content view. This works for the some labels but for some it just messes up.

I think I am fighting with two main issues here:

  1. When should I create dynamic subviews of the cell?

  2. How to dynamically resize a UIView (not UILabel) inside a UITableViewCell based on intrinsicSize of it's subViews.

  3. Can I use reusable cell identifier here as effectively each row is unique based on the content.

I am using the code provided by @smileyborg at https://github.com/smileyborg/TableViewCellWithAutoLayout

Community
  • 1
  • 1
tarun_sharma
  • 761
  • 5
  • 22

1 Answers1

4

The following key-points are considerable for proper dynamic height calculation of UITableViewCell for iOS 8 or later.

Cell Design Key-point:

  1. Set properly the content resistance priority and content hugging property of a subview , if there any dependency arises regarding to expansion or collapse , set the value of these priorities according to the cell requirement issues.
  2. For UILabel , set noofLines = 0 and content resistance property high to make the label size large if needed according the content size.
  3. If the content size is smaller than the actual size in cell , how much collapse can be considered , can be fit by content hugging priority .
  4. The interspacing size between subviews are depended accorinding to your wish

After satisfying these points

return UITabelViewAutomaticDimention from heightForRowAtIndexPath and estimatedHeightForRowAtIndexPath delegates methods , Hopefully , That works !!!

Rabindra Nath Nandi
  • 1,433
  • 1
  • 15
  • 28