13

I'm dynamically sizing a UITextView's height and the height of the UITableViewCell it is embedded in when its content changes. But I also have the ability to paste in predefined bits of texts.

As this pasting happens programmatically, the problem is, that after adding the selected text bit to the UITextView's text and calling my UITableView to update its cell heights, the UITextView hasn't yet updated its contentSize, which I use to calculate the cell's height.

Is there a way to force a UITextView to update its contentSize, after I programmatically add text to it?

Saad Chaudhry
  • 1,392
  • 23
  • 37
dkaisers
  • 824
  • 1
  • 8
  • 15
  • 1
    For future viewers, I believe the real answer to this question is `textView.sizeToFit()`. I'm using this in Swift 2.0 and it works perfectly, just as @dkaisers requested, as long as you're using AutoLayout. – kbpontius Aug 05 '15 at 22:18

2 Answers2

26

You can use sizeThatFits: to get the correct size.

CGFloat height = ceilf([textView sizeThatFits:textView.frame.size].height);

Here is a popular open source component that makes use of it to achieve dynamic resizing based on the textview content:   https://github.com/HansPinckaers/GrowingTextView

Manuel Escrig
  • 2,825
  • 1
  • 27
  • 36
Dima
  • 23,484
  • 6
  • 56
  • 83
4

Swift version of the answer:

var newTextViewHeight = ceil(textView.sizeThatFits(textView.frame.size).height)
textView.frame.size.height = newTextViewHeight

This piece of code might also come in handy if you want to update the superview of the UITextView

textView.superview?.frame.size.height = textView.contentSize.height + 10
Esqarrouth
  • 38,543
  • 21
  • 161
  • 168