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.
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.
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).
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.
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.
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.
© 2022 - 2024 — McMap. All rights reserved.