How to change UIView height based on elements inside it
Solution 1
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.
Solution 2
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
Solution 3
without auto layout code:
txtView.frame = CGRectMake(view.frame.origin.x + 8, view.frame.origin.y + 8, view.frame.size.width - 100, view.frame.size.height - 16);
btnSend.frame = CGRectMake(view.frame.size.width - 92, (view.frame.size.height/2) - 25, 84, 50);
Jason90
Updated on June 04, 2022Comments
-
Jason90 almost 2 years
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
-
Jason90 almost 8 yearsI am using aspect ratio constraint on my UIView so I am not able to use height constraint on it.
-
pajevic almost 8 yearsThen you should show us how you tried this. Because, if you are using autolayout (as you should), this is the way you would normally do it.
-
pajevic almost 8 yearsI have edited my answer. If it still doesn't solve your problem then tell us of any other constraints and how you are setting the height. Also if you are setting the
translatesAutoresizingMaskIntoConstraints
property.