4

Evening fellows, I got this problem:

I have a cell of a TableView. Inside the cell there are several elements nested into many stackViews, like in the picture.

One of this element is a TextView, witch has a constraint of height = 150, so I'm sure to display all the 300 characters that I set as limit to the textView.

But In case I have just few characters, I would like to have a different height for the textView, is there a way to autoresize it?

An other problem is that I had to set the row height = 220 of the TableView, so I'm pretty sure I need to autoresize it too.

Any tips? Thanks you enter image description here

Andrea Miotto
  • 7,084
  • 8
  • 45
  • 70
  • This question was marked as duplicate but the question linked is not the same. This question pertains specifically to the case of UITextViews and the answer given bellow pinpoints a very important step in the resolution being "This is an important setting to tell the textview to size itself accordingly based on its contents." Unfortunately, the question linked doesn't mention this and although someone mentions it in a comment, that comment is on the 7th answer down the page. I would really like the duplicate to be removed.. – Tokuriku Nov 06 '18 at 21:14

1 Answers1

14

You are able to use Auto Layout to achieve self-sizing table view cells with dynamic height.

First, allow the table view to use the Auto Layout constraints and the contents of its cells to determine each cell’s height, by setting the following:

tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 100 // Something close to your average cell height

Next, go to your storyboard and ensure that scrolling is disabled for your text view. This is an important setting to tell the textview to size itself accordingly based on its contents.

Leave out the height constraint for the textview because you want it to grow dynamically.

Finally, ensure that you have pinned the top of the textview to the bottom of the top label, and the bottom of the textview to the top of the bottom label. These labels should themselves be pinned to the top and bottom of the cell respectively, so that the cell can determine its total height from top to bottom.

You may also likely have to tweak the vertical compression resistance and the vertical hugging priority of the textview, to give Auto Layout a hint as to which view it should prioritise to compress or expand to fill up the cell space (Auto Layout should warn you on this in the storyboard).

Eneko Alonso
  • 18,884
  • 9
  • 62
  • 84
Ken Toh
  • 3,721
  • 1
  • 24
  • 30
  • Thank you so so much for mentioning **This is an important setting to tell the textview to size itself accordingly based on its contents.** Till date I knew that with only autolayout textview do not auturesize itself. Thank you again. – iPeter Mar 23 '18 at 07:41
  • Second this. Without this *important setting* nothing works – Arnie Schwarzvogel Jun 13 '18 at 11:15