【问题标题】:Swift3 iOS set UITextView height when line break happens发生换行时,Swift3 iOS设置UITextView高度
【发布时间】:2017-03-16 12:41:17
【问题描述】:

为了让我的 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 在您编写消息时不会共享此行为。

我在这里错过了什么?

【问题讨论】:

    标签: ios swift3 autolayout uitextview line-breaks


    【解决方案1】:

    使用以下代码:

    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
    }
    

    快乐编码。

    【讨论】:

    • 感谢您的帮助,但它的行为仍然像描述的那样:/
    • 请查看更新后的答案,这是我在项目中使用的代码。复制整个函数。它肯定会按需要工作。换行时尝试打印 newFrame 值。
    • 谢谢你的作品!我不得不禁用滚动。您知道启用滚动功能的方法吗?
    • 看看我的做法是我允许 textView 增长到包含 6 行文本。在此期间,滚动被禁用。在 textView 超过此值后,我启用滚动并且 textView 高度保持不变。
    • 这里是条件 if (newSize.height >= 40 && newSize.height = 100) { self.textView.isScrollEnabled = true }
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-02
    • 2013-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多