Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change UIView height based on elements inside it

I am creating a chat interface and have a UITextview and button for sending message inside a UIView. The height of UITextView changes based on its content size but UIView height does not change with it. Chat view

I will appreciate any help on this.

Here are constraints on the message field Message field constraints

like image 422
Jason90 Avatar asked Oct 24 '25 15:10

Jason90


2 Answers

If you programmatically created the view:

containerView.frame.size.height = textView.frame.size.height

If you create the view in the storyboard

Create a height constraint for your view. Then connect that constraint to your code. Then run this:

heightConstraint.constant = textView.frame.size.height
like image 103
Pranav Wadhwa Avatar answered Oct 27 '25 06:10

Pranav Wadhwa


Set autolayout constraints specifying a fixed space and pin them from your UIView top to the UITextView top and from your UIView bottom to the UITextView bottom.

It is unclear from your question how you are setting the height of your container view and your text view. You should have a height constraint on the text view and change its constant when you want to resize the text view. Do not change the frame directly. The container view must not have a height constraint - it should resize solely because of the bottom and top constraints to the text view.

like image 40
pajevic Avatar answered Oct 27 '25 06:10

pajevic