IOS UIView with dynamic height based on the number of elements inside

I need to dynamically create UIView

and show it as a cell in UITableView

or UIScrollView

.

How can I do this without manually calculating the height of the view (summing the heights of all elements)?

Example. I am programmatically adding 2 images and 10 texts that are vertically stacked on top of each other in the UIView. I take this UIView and put it in a cell content view or scroll view. How can I make sure the view expands so that it displays all the routines inside?

EDIT:

I guess the correct way would be to set vertical and horizontal constraints for each peek from top to bottom (including the bottom constraint for the last item).

The problem is that I cannot set a height limit for every element in a dynamic UIView, since those elements have dynamic heights too .

+3


source to share


2 answers


You don't need to add explicit height restrictions. The views that you add as subviews (images, labels) will have their own size. Just make sure you have leading, trailing, top and bottom constraints and the cell will resize.



+1


source


Rounak's answer is great, but incomplete.

For complex views that have nested objects inside, just create appropriate top-down and side-to-side constraints and that's enough. If you don't explicitly set the height limit, it will automatically set its own height.



For custom sheet views such as UILabel

or UIImageView

or MyCustomCircleImage

, you must override intrinsicContentSize

.

If AutoLayout does not have a top-down constraint relationship, it will face the inner dimension.

0


source







All Articles