Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would I (programmatically) set the height of a UITextView to its content size in Swift?

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.

like image 348
Benjy Wiener Avatar asked Mar 13 '15 20:03

Benjy Wiener


1 Answers

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.

like image 170
Stefan Arentz Avatar answered Sep 28 '22 13:09

Stefan Arentz