为了使我的 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
}
问题在于,当发生换行时,它确实会识别出大小的变化。如果你按回车,它不会调整大小,直到你添加另一个字符。如果您编写足够的文本以使其换行,也会发生同样的情况。它只会在您放入另一个字符后调整大小。当您删除一个字符以删除一行时,也会发生同样的情况,您必须删除另一个字符以调整高度。我觉得这看起来很草率,因为 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
}
快乐编码。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句