iosswiftuitextviewuitextviewdelegate

UITextView dynamic height scrolling doesn't work when long text is pasted


I've implemented changing the height of UITextView dynamically when height reaches a certain value by following this solution https://stackoverflow.com/a/38454252/12006517

This works fine however text view freezes when I paste a large chunk of text in it first time. After pasting large chunk of text it doesn't go to the end of text content and cursor disappears while text view freezes. I've to hit delete key and start entering then it starts to work fine.

Subsequent paste of large chunk of text works. So problem happens only pasting first time.

How do I fix this issue?

 class MyViewController: UIViewController {
    let messageTextViewMaxHeight: CGFloat = 200
 }

 extension MyViewController: UITextViewDelegate {

    func textViewDidChange(_ textView: UITextView) {

        if textView.contentSize.height >= self.messageTextViewMaxHeight {
            textView.isScrollEnabled = true
        } else {
            textView.frame.size.height = textView.contentSize.height
        }

    }

 }

Solution

  • You can try below code. It working fine.

    func textViewDidChange(_ textView: UITextView) {
    
        let sizeThatShouldFitTheContent = textView.sizeThatFits(textView.frame.size)
        if sizeThatShouldFitTheContent.height  > 120 {
            textView.isScrollEnabled = true
        }else{
            textView.isScrollEnabled = false
        }
    }