如何防止自调整大小的 UITextView 超过特定点(例如键盘顶部锚点)?

How can I prevent a self-sizing UITextView from growing past a specific point (keyboard top anchor, e.g.)?

我有一个 UITextView,它会根据用户的文本输入自动增长。

我想防止 UITextView 的底部锚点进入键盘下方,或者我想在用户输入文本时自动滚动视图本身,这使得文本视图超过键盘顶部(进入键盘,如果你愿意的话),这样他们正在输入的视图可以在输入时显示。关于如何解决这个问题有什么建议吗?

我应该在执行此操作的视图控制器中配置滚动视图吗?

我现在的代码是这样的:

    let textView: CustomTextView = {
           
    ///Set bio Box text view:
    let field = CustomTextView()
            
     field.textColor = .label
     field.layer.borderWidth = 1
     field.layer.cornerRadius = 10
     field.font = Fonts.createSize(14)
     field.keyboardAppearance = .default
     field.tintColor = Colors.mainBrandColor
     field.placeholderLabel.text = "Tell us about yourself..."
     field.layer.borderColor = UIColor(named: "customTopColorControl")?.cgColor
            
     field.translatesAutoresizingMaskIntoConstraints = true
     field.sizeToFit()
     field.isScrollEnabled = false
     return field
  }()

  ///Setup text view:
  func setupTextView() {
    addSubview(textView)

    textView.anchor(
      top: titleLabel.bottomAnchor,
      left: leftAnchor,
      bottom: inputAccessoryView?.topAnchor,
      right: rightAnchor,
      paddingTop: 20,
      paddingLeft: 20,
      paddingBottom: 0,
      paddingRight: 20,
      width: 0,
      height: 0)
  }

  ///Adjusts the textview to fit the size of the text within it:
  func adjustUITextViewHeight(textView: UITextView) {
     textView.translatesAutoresizingMaskIntoConstraints = true
     textView.sizeToFit()
     textView.isScrollEnabled = false
  }

一个简单的解决方案是对 textView 进行高度限制。将 textView 的 isScrollEnabled 属性 设置为 false。让它增长直到它到达键盘原点(你必须以编程方式检查它)。一旦到达键盘原点,固定高度并将 isScrollEnabled 属性 设置为 true