Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 288
MEnnabah Avatar asked Dec 08 '22 17:12

MEnnabah


1 Answers

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

like image 161
MEnnabah Avatar answered Dec 27 '22 13:12

MEnnabah