Search code examples
iosobjective-cswifttextviewuitextview

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.


Solution

  • 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