【问题标题】:Expand UITextView and then scroll after certain point展开 UITextView 然后在某个点后滚动
【发布时间】:2019-11-12 14:38:28
【问题描述】:

我一直在努力设置创建这个,我在这里阅读了很多帖子,但不明白我做错了什么。

我有一个UITextView

我希望它的高度扩大到一个数字,然后在启用滚动的情况下固定在该高度。

我已经设置了我的UITextFieldDelegate并添加了以下内容-

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

这样做可以让 继续增长。

我现在希望它停止并在例如高度为 100 处滚动。

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

        let newHeight = min(100, newSize.height)

        textView.frame.size = CGSize(width: 0, height: newHeight)

        textView.isScrollEnabled = newHeight >= 100
    }

此时发生的所有事情都是当isScrollEnabled 设置为true 时滚动视图缩小。

我的 textView 仅锚定到其父级的 topleadingtrailing

启用滚动后如何强制它不折叠?

编辑

我添加了以下内容,但在固定高度状态下输入任何内容时,文本似乎“摇晃”

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

        let newHeight = min(100, newSize.height)

        textView.frame.size = CGSize(width: 0, height: newHeight)

        if newHeight >= 100 {
            textView.isScrollEnabled = true
            textView.heightAnchor.constraint(equalToConstant: 100).isActive = true
        } else {
            textView.isScrollEnabled = false
            textView.heightAnchor.constraint(equalToConstant: 100).isActive = false
        }
    }

【问题讨论】:

    标签: swift autolayout uitextview uitextviewdelegate cgsize


    【解决方案1】:

    最好做一个默认的高度约束并连接它的出口并使用它的常量

    self.txH.constant = newHeight
    self.view.layoutIfNeeded()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-28
      • 1970-01-01
      相关资源
      最近更新 更多