When you try and do a sizeThatFits
on a UITextView, if you then set the height of said UITextView to the result, then it's too short! This answer:
UITextView Content Size too Short
Also seems to fall short as, if you examine the contentInset
property of the text view, the contentInset
is all set to zeroes.
The key it use textContainerInset
rather than contentInset
. This will give you the proper buffer on the top and bottom that you're looking for. So, you'll get something like:
textView.text = "Some multiline text";
let size: CGSize = textView.sizeThatFits(CGSizeMake(textView.frame.size.width, CGFloat.max));
let insets: UIEdgeInsets = textView.textContainerInset;
textViewHeight.constant = size.height + insets.top + insets.bottom;
It's also important to note, that this method must be called after the UITextView has been rendered. In other words, I originally was resizing this in the viewDidLoad
method of the controller, when in actuality it had to be in viewDidAppear
. This is annoying since the view is already displayed, but I solved it by fading in the few for better aesthetics.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With