UIView with dynamic height that uses intrinsicContentSize
Solution 1
To answer my own question, it appears that there is not an autolayout suitable solution to this situation. Looking to UILabel
for inspiration, the problem here has been solved with the addition of a property preferredMaxLayoutWidth
, which can then be used as a constraining width during the intrinsic content size calculation. Any custom view would need to use something similar.
Solution 2
I think the doc means that, your containerView
might have a placeHolderFrame
as content frame.
intrinsic size should not be related to the content frame, but only to it's own subContent. Your image and UILabel for example.
You should calculate both height and the width from the label and the image. Which should be easy, since they all have intrinsic size.
Just my opinion...
Related videos on Youtube
Tark
Updated on September 15, 2022Comments
-
Tark over 1 year
I am trying to create a custom container view that has a UIImageView and a multiline UILabel as subviews. To make the view work nicely with autolayout, I am overriding intrinsicContentSize as below:
- (CGSize)intrinsicContentSize { return [self sizeThatFits:self.bounds.size]; }
The size calculated in sizeThatFits has the same width, and adjusts the height so that the label and image are not clipped. This works well, but I was surprised to see in the docs the following comment:
This intrinsic size must be independent of the content frame, because there’s no way to dynamically communicate a changed width to the layout system based on a changed height, for example.
If that is the case, what is the autolayout way to adjust the views current height based on its width and content? Should I be approaching this in a different way?
-
TarkThe compression resistance is the priority at which a view resists being made smaller than its intrinsic content size. If the intrinsic content size is not correct, then this is not going to be of much use.
-
-
Tark over 10 yearsWhat is a placeHolderFrame? For that matter, what is a content frame? The label is a multiline label, it is not possible to know what its height will be without first knowing how much width the view has to wrap text into.
-
Tark over 10 yearsThe problem here is not how to layout the view correctly, it is to tell the layout system the intrinsic height of the view, so that it is given the correct height depending on its content.
-
MANIAK_dobrii over 10 yearsMy point it about intrinsic contentSize of a label. With preferredMaxLayoutWidth it can be updated in a more autolayout-friendly way (maybe that's how apple suggests to do things).
-
Yevhen Dubinin over 9 yearsYes, seems like there is almost no help from Autolayout to accomplish it. Your answer made me think about the approach where we constraint the view width when
preferredMaxLayoutWidth > 0.0f
, and literally don't constraint otherwise - use a big float (e.g. 99999.0f) for width in intrinsic content size calculation.