Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a view height grow depending on its child views contents

I have a parent view whose height has to be decided by its child content.

How may I achieve this in storyboard without programatically changing it.

like image 930
Ranjith kumar Avatar asked Oct 19 '17 16:10

Ranjith kumar


2 Answers

You can accomplish this using AutoLayout.

Make sure each of the child views has constraints defining its size and position. Then, set the parent view's vertical content hugging and compression resistance priorities to required. This will define the parent's height based on the height and positioning of its child views.

Note that depending on what the child views are, you may want to change their vertical content hugging and compression resistance priorities as well. For example, a UILabel with numberOfLines set to 0 can automatically grow based on its content, so you'd want it to hug its content vertically and resist vertical compression so that it resizes the parent view.

This image shows the parent (white) view with its vertical hugging and compression resistance priorities set in the inspector panel. Notice that the parent view has constraints set for its width, x-position, and y-position, but not its height. It's able to infer its height based on the height and position of the child views (see the next image).

enter image description here

This image shows the constraints of each child view. Notice that the vertical hugging and compression resistance priorities of these views were not changed. Each of these views has constraints for x-position and y-position, but you'll notice that not all of them have constraints for width and height. Views like the label and switch are able to automatically infer their size constraints based on their content. If you don't set vertical position constraints on every one of the child views, AutoLayout won't know how much space each of them needs, so it won't know how tall the parent view should be.

enter image description here

like image 62
John Wickham Avatar answered Nov 04 '22 04:11

John Wickham


1- Add you View container and add constraints. Don't set height nor bottom spacing or set it but with less priority (example 999).

2- Add items/things to your View Container and add constraints. Be sure to add all require constraints plus add bottom spacing to the bottom item inside.

That will define the height of the container View.

enter image description here

enter image description here

PD: Forget about Content Hugging/Compression and Priority. They are handy but no use here. They just set a resistance to get bigger or smaller.

like image 25
alegelos Avatar answered Nov 04 '22 02:11

alegelos