iosautolayoutuistoryboardnslayoutconstraintios-autolayout

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.


Solution

  • 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