Dynamically adjust the height of the UITextView depending on its content?

9.7k views Asked by At

I have an UITextView that loads different text depending on the route the user has taken in order to get to the view with the text on it.

How do I dynamically adjust the height of the UITextView depending on its content using Swift?

1

There are 1 answers

1
keithbhunter On BEST ANSWER

Setup your constraints so that the edges are pinned but allow the text view to grow vertically. Then set a height constraint (the value doesn't matter here). Create an @IBOutlet for the UITextView and the height constraint. Then we can dynamically change the height in code:

class ViewControler: UIViewController, UITextViewDelegate {

    @IBOutlet weak var textView: UITextView!
    @IBOutlet weak var textViewHeight: NSLayoutConstraint!


    override func viewDidLoad() {
        super.viewDidLoad()
        self.textView.delegate = self
    }

    func textViewDidChange(textView: UITextView) {
        let sizeToFitIn = CGSizeMake(self.textView.bounds.size.width, CGFloat(MAXFLOAT))
        let newSize = self.textView.sizeThatFits(sizeToFitIn)
        self.textViewHeight.constant = newSize.height
    }

}