Ennabah
Ennabah

Reputation: 2513

Expand UITextView based on its content

I'm trying to expand my UITextView to change the frame based on its content.

The textView should resize its height when the text inside of it gets larger, and smaller when the user deletes the text.

I tried many answers but it didn't work.

Upvotes: 5

Views: 6823

Answers (2)

john07
john07

Reputation: 560

Under Autolayout use invalidateIntrinsicContentSize() for UITextView

func viewDidLoad(){
    textView.delegate = self;
    textView.isScrollEnabled = false;
}

extension Chat:UITextViewDelegate {
  func textViewDidChange(_ textView: UITextView) {
    textView.invalidateIntrinsicContentSize();
  }
} 

Upvotes: 0

Ennabah
Ennabah

Reputation: 2513

Using the following two lines are the best answer for the question, and it solved my problem:

expandingTextView.textContainer.heightTracksTextView = true
expandingTextView.isScrollEnabled = false

Notes:
expandingTextView: UITextView.
textContainer: NSTextContainer is the bounds of the text inside the expandingTextView.
heightTracksTextView: Bool If true, the reciever will adjust its height based on the expandingTextView height.

In order to the expanding to work, you need to disable the textView scrolling by:
isScrollEnabled = false

Upvotes: 20

Related Questions