菜鸟教程小白 发表于 2022-12-11 18:59:33

ios - 当文本达到 N 行时开始滚动的 UITextView


                                            <p><p>我开始在聊天应用中实现文本输入,我想知道启用滚动的 UITextView 的标准行为绝对不符合预期。<br/>
我只想在 WhatsApp 之类的聊天中完成。当文本达到 N,例如 5 行时,会出现滚动条并且文本容器开始滚动。我写了这样的代码,但它不起作用。
正如我认为需要计算文本容器中的行并制作内容插入或类似的东西。</p>

<pre><code>   func textViewDidChange(_ textView: UITextView) {
      let fixedWidth = myTextView.frame.size.width
      myTextView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))
      let newSize = myTextView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))
      var newFrame = myTextView.frame
      let oldFrame = myTextView.frame
      newFrame.size = CGSize(width: max(newSize.width, fixedWidth), height: newSize.height)
      myTextView.frame = newFrame
      let shift = oldFrame.height - newFrame.height
      textView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: shift, right: 0)
      textView.scrollIndicatorInsets = textView.contentInset
      textView.scrollRangeToVisible(textView.selectedRange)
    }
</code></pre>

<p>而myTextView被指定为:</p>

<pre><code>let myTextView : UITextView = {
      let textView = UITextView()
      textView.translatesAutoresizingMaskIntoConstraints =false
      textView.isScrollEnabled = false
      textView.textContainer.maximumNumberOfLines = 5
      textView.textContainer.lineBreakMode = .byWordWrapping
      textView.inputAccessoryView = UIView()
      return textView
    }()
</code></pre></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>不是基于行数,而是基于用户定义的高度。你会在这里找到你的答案:
<a href="https://stackoverflow.com/a/51235517/10115072" rel="noreferrer noopener nofollow">https://stackoverflow.com/a/51235517/10115072</a> </p></p>
                                   
                                                <p style="font-size: 20px;">关于ios - 当文本达到 N 行时开始滚动的 UITextView,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/42235360/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/42235360/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - 当文本达到 N 行时开始滚动的 UITextView