Reputation: 681
To make my textView resize its height with the content, i use the following code:
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
let contentSize = textView.sizeThatFits(textView.bounds.size)
self.textViewHeight.constant = contentSize.height
//textViewHeight is the height constraint of the textView defined in the storyboard.
return true
}
The problem is that it does recognize a change in size when a line break happens. If you press return, it will not resize until you add another character. The same happens if you write enough text for it to make a line break. It will only resize after you put in another character. The same happens when you delete a character to remove a line, you will have to remove another character to resize the height. I feel this looks sloppy since iMessage and Whatsapp do not share this behavior when you write your messages.
What am I missing here?
Upvotes: 3
Views: 1578
Reputation: 5477
Use the following Code:
func textViewDidChange(_ textView: UITextView) {
let fixedWidth = textView.frame.size.width
let newSize = textView.sizeThatFits(CGSize.init(width: fixedWidth, height: CGFloat(MAXFLOAT)))
var newFrame = textView.frame
newFrame.size = CGSize.init(width: CGFloat(fmaxf(Float(newSize.width), Float(fixedWidth))), height: newSize.height)
self.textViewHeight.constant = newSize.height
}
Happy Coding.
Upvotes: 3