Reputation: 3664
I need to create an UIView
dynamically and show it as a cell in UITableView
or UIScrollView
.
How can I do this without manually calculating the height of the view (summing up the height of all elements) ?
Example: I programatically add 2 images and 10 texts that are stacked vertically on each other in a UIView. I take this UIView and put it in a cell content view, or scroll view. How do I make sure that the view expands itself so it shows all the subviews inside ?
EDIT:
I guess the proper way would be to set the vertical and horizontal constraints for each subview from top to bottom (including the bottom constraint for the last element).
The problem is that I can't set the height constraint for each element in the dynamic UIView, as these elements have a dynamic height too.
Upvotes: 4
Views: 3525
Reputation: 3664
Rounak's answer is great but not complete.
For complex views that have subviews inside just create the appropriate constraints from top to bottom and sides and that's enough. If you don't set the height constraint explicitly, it'll set it's own height automatically.
For custom leaf views like UILabel
or UIImageView
or MyCustomCircleImage
you have to override intrinsicContentSize
.
If AutoLayout doesn't have the connection of constraints from top to bottom, it'll turn to the intrinsic size.
Upvotes: 0
Reputation: 9397
You don't need to add explicit height constraints. The views you'll add as subviews (image views, labels) will have their own intrinsic size. Just make sure you have leading, trailing, top and bottom constraints, and the cell will resize itself.
Upvotes: 1