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

天大地大妈咪最大 提交于 2019-12-11 19:34:04

问题


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
        }

    }

 }

回答1:


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
    }
}


来源:https://stackoverflow.com/questions/57996778/uitextview-dynamic-height-scrolling-doesnt-work-when-long-text-is-pasted

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!