如何调整 UITextView 的大小,当达到特定值时,它会根据内容和固定宽度自动调整其宽度和高度?

How to resize a UITextView that automatically resize its width and height based on the content and fixed width when reaches certain value?

我曾尝试使用以下代码创建自动调整大小的 UITextView。

func textViewDidChange(_ textView: UITextView) {
     let fixedWidth = textView.frame.size.width
     let newSize = textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))
     textView.frame.size = CGSize(width: max(newSize.width, fixedWidth), height: newSize.height)

}

当我输入第一个字符时,它不会根据字符调整宽度。我尝试的另一个解决方案是这个。

 func textViewDidChange(_ textView: UITextView) {
     let fixedWidth = textView.frame.size.width
     let newSize = textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))
     textView.frame.size = CGSize(width: newSize.width, height: newSize.height)

}

它的宽度停留在第一个字符上,这个解决方案每行只有一个字符。我该如何解决这个问题?

试试这个:

    let maximumWidth: CGFloat = 200 // Change as appropriate for your use.
    let newSize = textView.sizeThatFits(CGSize(width: maximumWidth, height: CGFloat.greatestFiniteMagnitude))
    textView.frame.size = CGSize(width: newSize.width, height: newSize.height)

您需要想出一种方法来确定最大宽度,因为我现在已经硬编码了它。

这会将 UITextView 水平扩展到 200 点,然后开始垂直扩展。