Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 946
Pete.Mertz Avatar asked Mar 18 '15 12:03

Pete.Mertz


1 Answers

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.

like image 184
Pete.Mertz Avatar answered Oct 22 '22 07:10

Pete.Mertz