9

I have a UITextView called recipeDesc. I would like to have an option within my app to dynamically adjust the height of the UITextView to fit the content (text) inside the UITextView (so I need to know how to do it programmatically). I found some answers for Objective-C, but I am not very familiar with it, so I don't know how to implement it in Swift.

Thanks in advance for any help.

Benjy Wiener
  • 1,085
  • 2
  • 9
  • 27

1 Answers1

16

You can get the ideal content size for your UITextView simply with:

let contentSize = textView.sizeThatFits(textView.bounds.size)

So after that, you can adjust it's frame with that height:

var frame = textView.frame
frame.size.height = contentSize.height
textView.frame = frame

(I originally had used textView.contentSize.height but that does not work when the view has not rendered yet. For example in viewDidLoad)

If you use Auto Layout, the rules are a bit different. Update your question if you do.

Stefan Arentz
  • 34,311
  • 8
  • 67
  • 88
  • I have also some troubles and I use autolayout: http://stackoverflow.com/questions/29431968/how-to-adjust-the-height-of-a-textview-to-his-content-in-swift I tried to use your code but it doesn't work in my case. – cmii Apr 03 '15 at 19:55