Home > OS >  UITextView contentSize is not update after paste swift iOS
UITextView contentSize is not update after paste swift iOS

Time:05-15

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)")

}

CodePudding user response:

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.

  • Related