【问题标题】:UITextView doesn't print text on the nextLine?UITextView 不在 nextLine 上打印文本?
【发布时间】:2019-05-15 17:11:30
【问题描述】:

我将 UITextView 放在 UIView 中。 UIView 会随着用户在 UITextView 中键入而扩展,但问题是如果用户在下一行键入,它不会显示正在键入的文本,直到用户在第三行键入,然后它会显示打印在第二行。第 3 行和第 4 行等也是如此。

我该如何解决这个问题?

func textViewDidChange(_ textView: UITextView) {
    print(textView.text)
    let size = CGSize(width: prayerRequest.frame.width, height: .infinity)

    let estimatedSize = textView.sizeThatFits(size)
    textView.constraints.forEach { (constraints) in
        if constraints.firstAttribute == .height {
            constraints.constant = estimatedSize.height

        }

        viewContainer.constraints.forEach({ (constraints) in
            if constraints.firstAttribute == .height {
                constraints.constant = estimatedSize.height
                viewContainer.layoutIfNeeded()
            }
        })
    }

}

【问题讨论】:

  • 试试view.layoutIfNeeded()而不是viewContainer.layoutIfNeeded()
  • @Sh_Khan 现在试过了,它仍然做同样的事情:(

标签: ios swift uitextview


【解决方案1】:

如果您使用的是界面生成器,请尝试将行数设置为 0。

或来自代码textView.textContainer.maximumNumberOfLines = 10

【讨论】:

    【解决方案2】:

    首先,你不需要为 textView 的 Parent 设置高度。即使您确实为 textView 的父级设置了低优先级。

    看图片,紫色是父级,黄色是textView。

    在viewDidLoad中,添加如下代码:

    textView.textContainerInset = UIEdgeInsets.zero
    textView.textContainer.lineFragmentPadding = 0
    

    然后,实现 textView Delegate 方法:

    extension ViewController : UITextViewDelegate {
        func textViewDidChange(_ textView: UITextView) {
            let textHeight = textView.attributedText.boundingRect(with: 
                CGSize.init(width: textView.frame.width, height: .infinity),
                   options:[.usesLineFragmentOrigin, .usesFontLeading],
                   context: nil).height
    
            if previousHeight != textHeight {
                previousHeight = textHeight
                print("Height text: \(textHeight)")
                textViewHeight.constant = textHeight
                self.view.layoutIfNeeded()
                textView.setContentOffset(.zero, animated: false)
            }
        }
    }
    

    textViewHeight 是 textView 的高度限制。 将var previousHeight = CGFloat(0) 初始化为实例变量。它将有助于将 layoutIfNeeded 的调用限制为仅在更改高度时调用。

    textView 的底部约束将展开父视图。所以你也不需要设置父母的高度。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-08
      • 1970-01-01
      • 1970-01-01
      • 2020-06-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多