Search code examples
iosswifttextview

UITextView calculates height wrong if text input by copy paste


func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {

    let fixedWidth: CGFloat = textView.frame.size.width

    let newSize: CGSize = textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))

    delegate.updateHeightTextView(height: newSize.height)

    return true
}

I calculate the textview height in above function. It works well when I type in some text, but when I copy and paste text, it isn't correct.


Solution

  • I found solution. Instead of calculate height textview in - (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text; I calcuated it in - (void)textViewDidChangeSelection:(UITextView *)textView;

    If I calculate in textViewDidChange It's not called if I type first charactor or paste some text at first.