Search code examples
iosswiftscrolluitextview

How to change the TextView height dynamically to a threshold and then allow scrolling?


I have a TextView that has a constraint of min height of 33. The scroll is disabled from the storyboard. The TextView should increase in height based on the content until it reaches the max height of 100. Then I changes the scrollEnabled to true and the height of the TextView to max height of 100, but the height changes to the 33. How can I fix this problem?

import UIKit

class ViewController: UIViewController, UITextViewDelegate {

    @IBOutlet weak var messageTextView: UITextView!
    let messageTextViewMaxHeight: CGFloat = 100
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.messageTextView.delegate = self
    }
    
    func textViewDidChange(textView: UITextView) {
        
        if textView.frame.size.height >= self.messageTextViewMaxHeight {
            textView.scrollEnabled = true
            textView.frame.size.height = self.messageTextViewMaxHeight
        } else {
            textView.scrollEnabled = false
        }
    }
}

enter image description here


Solution

  • It seems your code requires two changes, and it will work fine.

    1. Instead of min height of constraint provide max height of 100:

    Height Constraint for TextView

    1. Change code as below:

       import UIKit
      
      class ViewController: UIViewController, UITextViewDelegate
      {
          @IBOutlet weak var messageTextView: UITextView!
      
          let messageTextViewMaxHeight: CGFloat = 100
          override func viewDidLoad()
          {
              super.viewDidLoad()
              messageTextView.delegate = self
          }
      
          func textViewDidChange(textView: UITextView)
          {
              if textView.contentSize.height >= self.messageTextViewMaxHeight
              {
                  textView.scrollEnabled = true
              }
              else
                  {
                  textView.frame.size.height = textView.contentSize.height
                  textView.scrollEnabled = false // textView.isScrollEnabled = false for swift 4.0
              }
          }
      }