0

I have a textView on chatScreen. I need to know, how it possible to increase the height of the textView when we will write 3 or more lines. Here is how it looks in my app: enter image description here

I've implemented this method:

override func textViewDidChange(_ textView: UITextView) {
        super.textViewDidChange(textView)

Here is an example from WhatsApp, how it should look like: enter image description here

Fahim Parkar
  • 30,974
  • 45
  • 160
  • 276
mozeX
  • 23
  • 7
  • Does any of this helps : https://stackoverflow.com/questions/38714272/how-to-make-uitextview-height-dynamic-according-to-text-length ? – Rob Mar 24 '22 at 13:26
  • No, I've tried some solution from this post but it's not what I need – mozeX Mar 24 '22 at 13:40

1 Answers1

0

You need to:

  • constrain the Bottom of the text view
  • give it a minimum height
  • disable scrolling of the text view

Quick example:

class QuickExampleViewController: UIViewController {
    
    let textView = UITextView()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // so we can see it
        textView.backgroundColor = .cyan

        // disable scrolling
        textView.isScrollEnabled = false

        // set the font
        let font: UIFont = .systemFont(ofSize: 20.0, weight: .light)
        textView.font = font
        
        // we want the height to be at least one-line high
        //  even if it has no text yet
        let minHeight: CGFloat = font.lineHeight
        
        textView.translatesAutoresizingMaskIntoConstraints = false

        view.addSubview(textView)
        
        let g = view.safeAreaLayoutGuide
        NSLayoutConstraint.activate([
            // Leading / Trailing -- will likely be based on other UI elements
            textView.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 60.0),
            textView.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: -60.0),
            // Bottom constraint, so it will "grow up"
            textView.bottomAnchor.constraint(equalTo: g.topAnchor, constant: 300.0),
            // at least minHeight tall
            textView.heightAnchor.constraint(greaterThanOrEqualToConstant: minHeight),
        ])
        
    }
}
DonMag
  • 69,424
  • 5
  • 50
  • 86