'UITextView contentSize is not update after paste swift iOS

When I paste some text, textview height of contentSize is not correct. It returns text height before paste.

For example,

I expect height value : [contentSize Height] 1019 (after paste) But real value : [contentSize Height] 540 (before paste)

I tried setNeedDisplay() method, but it's not working.

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool
{
    print("[contentSize] \(textView.contentSize.height) size to fit \(textView.sizeThatFits(view.frame.size).height)")

}


Solution 1:[1]

When textView(_:shouldChangeTextIn:replacementText:) is called the text hasn't been applied to the view yet which means the contentSize has not changed. If possible, you can use textViewDidChange(_:), it should print the correct size.

func textViewDidChange(_ textView: UITextView) {
    print("[contentSize] \(textView.contentSize.height) size to fit \(textView.sizeThatFits(view.frame.size).height)")
}

If you really need to calculate the size of the text on the shouldChangeTextIn method, you could try calculating the size using an approach like this.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Claudio