iosswiftuitextviewswift5uitextviewdelegate

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


I have a UITextView, which automatically grows according to the user's text input.

I'd like to prevent the UITextView's bottom anchor from going under the keyboard, or I'd like to autoscroll the view itself as the user inputs text which makes the textview surpass the top of the keyboard (go under the keyboard, if you will), so that the view they are typing in can be displayed while the typing occurs. Any suggestions on how to go about this?

Should I configure a scroll view in the view controller I'm doing this in?

My current code is this:

    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
  }

Solution

  • A simple solution is to give a height-constraint to the textView. Set isScrollEnabled property of the textView to false. Allow it to grow until it reaches the keyboard origin(you have to check this programmatically). Once it reaches the keyboard origin, make the height fixed and set isScrollEnabled property to true