【问题标题】:UITextView: Automatically break line when reached a fixed widthUITextView:达到固定宽度时自动换行
【发布时间】:2018-04-28 19:21:47
【问题描述】:

我正在开发一个包含 UITextView 的视图。估计内容的正确高度可以正常工作,但是当连续键入内容时,内容会在边框上水平增长。看起来像这样:

是否有任何方便的解决方案可以在达到通过自动布局定义的最大宽度时自动换行?

【问题讨论】:

  • 可能的解决方法:在属性检查器中,将“行”设置为 2 或更多。
  • 我正在使用没有“行”属性的 UITextView

标签: swift dynamic view width uitextview


【解决方案1】:

我想出的解决方案是一个非常简单的方法:

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    let size = textView.sizeThatFits(textView.frame.size)
    if size.width >= self.maxTextViewWidth {
        let subString = textView.text.suffix(1)
        textView.text.removeLast(1)
        textView.text.append(contentsOf: "\n" +  subString)
    }

    return true
}

【讨论】:

  • 粘贴长文本后,每输入一个字符都会换行
【解决方案2】:

如果您想修复字符或行数的限制,您可以通过实现来自 UITextView 委托的方法,称为 func textView(UITextView, shouldChangeTextIn: NSRange, replacementText: String)

【讨论】:

  • 这种行为并不是我想要的。我希望我的应用程序在文本中添加一个换行符,而不是在边界上增长
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-29
  • 1970-01-01
相关资源
最近更新 更多