Dynamically change parent UIView’s height when TextView height changes

I have been working on a new app for the last few weeks and yesterday I ran into a small problem. I have a UITextView in a UIView container and I want the UITextView’s height to dynamically change as the user type in it. However, I also want the parent container’s height to increase as well. I broke this problem down in two sections:

  1. Dynamically change UITextView’s height
  2. Dynamically change container’s height.

First let’s start with UITextView’s height. There are plenty of ways you can do this, I decided to use UITextViewDelegate and it’s function ‘TextViewDidChange()’ to calculate the height of the textview. This function is called every time user types in the textview. Since I am not using storyboards for this project I have set all the constraints programmatically. Obviously for a certain element to increase it’s height dynamically you need to keep any one side of the element constraint-free.

Since I wanted the UITextView to move up when a new line is added, I decided to remove the top constraint of the TextView. Here are the constraints for the UITextView:

Since we have not anchored the textview to the top, we need to provide it with a default height. First declare a variable of type NSLayoutConstraint?

Then in the class section add this delegate:
Don’t forget to set textview.delegate to self. Now we will provide the textview a constant height of 35.

Then we will create a function that will be called every time the user types something in the textview. The function called adjustheight() will look at the contentsize and set the textview height accordingly.

Call this function in viewDidLoad or wherever you are setting up constraints for the views & textviewDidChange() -> note that this function comes with the UITextViewDelegate.

This will dynamically set the height of the textview. Now we will change the height of the parent UIView container. If we don’t do this step the parent container will remain where it is and the textview will keep moving up. So in order to fix this we will find the difference of the newSize from the constant height set earlier. Here is how:

We will do the same thing with the container view by setting the height constant at 84 as constant and creating a containerHeightConstraint variable just like we did with the textView.

We will add the above two lines in the adjustTextViewHeight() function:

And that’s it basically. Now when the textView height increases, the background container’s height also increases.

Leave a Reply

Your email address will not be published. Required fields are marked *