Swift3 iOS 换行时设置 UITextView 高度

Swift3 iOS set UITextView height when line break happens

为了使我的 textView 根据内容调整其高度,我使用以下代码:

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    let contentSize = textView.sizeThatFits(textView.bounds.size)
    self.textViewHeight.constant = contentSize.height

    //textViewHeight is the height constraint of the textView defined in the storyboard.

    return true
}

问题是当发生换行时它确实识别出大小的变化。如果您按 return,它不会调整大小,直到您添加另一个字符。如果您为它写了足够多的文本来换行,也会发生同样的情况。它只会在您输入另一个字符后调整大小。当您删除一个字符以删除一行时,也会发生同样的情况,您将不得不删除另一个字符以调整高度。我觉得这看起来很草率,因为 iMessage 和 Whatsapp 在您编写消息时不会共享此行为。

我在这里错过了什么?

使用以下代码:

func textViewDidChange(_ textView: UITextView) {
let fixedWidth = textView.frame.size.width
let newSize = textView.sizeThatFits(CGSize.init(width: fixedWidth, height: CGFloat(MAXFLOAT)))
var newFrame = textView.frame
newFrame.size = CGSize.init(width: CGFloat(fmaxf(Float(newSize.width), Float(fixedWidth))), height: newSize.height)
self.textViewHeight.constant = newSize.height
}

编码愉快。