UITextView sizeThatFits gives an answer that's too short in Swift
Asked Answered
C

1

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.

Chops answered 18/3, 2015 at 12:50 Comment(0)
C
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.

Chops answered 18/3, 2015 at 12:50 Comment(1)
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!Madancy

© 2022 - 2024 — McMap. All rights reserved.