4

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.

Daniyar
  • 2,975
  • 2
  • 26
  • 39
michal.ciurus
  • 3,616
  • 17
  • 32

2 Answers2

1

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.

rounak
  • 9,217
  • 3
  • 42
  • 59
  • I got the idea that views need to have explicit height constraints from the designer. For example when I create two views that have top,left,right, bottom constraints I get a "Missing Constraints" error: http://grab.by/IH1s. – michal.ciurus Jul 09 '15 at 12:20
  • @michal.ciurus are these plain UIViews? They don't have an intrinsic size. But if you're using something like an image view or a label, they will have an intrinsic size. – rounak Jul 09 '15 at 12:24
  • 1. UILabel doesn't show these errors. UIIMageView does. http://grab.by/IH1W 2. `intrinsicContentSize` is inherited from UIView, hence UIView does have intrinsic size. https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIView_Class/index.html#//apple_ref/occ/instm/UIView/intrinsicContentSize – michal.ciurus Jul 09 '15 at 12:27
  • 1
    Actually the answer for that is here: http://stackoverflow.com/questions/26833627/with-auto-layout-how-do-i-make-a-uiimageviews-size-dynamic-depending-on-the-im The bottom line is: "Missing Constraints" is not always bad. You can define intrinsic size for UIView. – michal.ciurus Jul 09 '15 at 12:32
  • But what if this UIView is inside another UIView? – Zonily Jame Dec 05 '16 at 06:51
0

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.

michal.ciurus
  • 3,616
  • 17
  • 32