6

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.

Community
  • 1
  • 1
Pete.Mertz
  • 1,302
  • 2
  • 18
  • 34

1 Answers1

19

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.

Pete.Mertz
  • 1,302
  • 2
  • 18
  • 34
  • 2
    thanks!! I override `viewDidLayoutSubviews()` in my viewcontroller and call the method it works flawlessly! previously I called the method in `viewDidLoad` and wonder why it wasn't working! – user3162662 Dec 07 '15 at 10:26