DanZimm
DanZimm

Reputation: 2568

Rigid Constraints vs. `-intrinsicContentSize`

So I recently was creating what Apple calls a leaf-level view (a button) and so I followed Apple's docs to implement -intrinsicContentSize and everything worked (albeit the code felt a bit weird - I had constraints set up in my -updateConstraints method to position subviews, as well as code in the -intrinsicContentSize method to calculate what the total size should be; it felt like I was giving duplicate information to the autolayout system).

However, I also ran into a post on here claiming to, instead of using -intrinsicContentSize, use rigid constraints and then the containerview will automatically resize to fit the views it contains. I also implemented this, and achieved the same result as above, but this time I didn't feel like I was duplicating information sent (I just sent the straight constraints). Note that I see the view as described in the post mentioned above as a so called leaf-level view since it doesn't sound like any other view would be added to it.

Which implementation of resizing a container view based on the content inside of it is the proper way to go?


I'm currently leaning towards the second method, due to the fact that I don't think I should be sending duplicate information, however Apple's documentation says otherwise (then again, Apple's docs can be a bit confusing/misleading at times).


Sidenote about my specific situation, f it matters: I have two subviews in my button, one being an image, the other being a label. The image gets it's size from the label, and then the entire button from the image (so indirectly the sizing comes entirely from the label).

Upvotes: 0

Views: 164

Answers (1)

jrturton
jrturton

Reputation: 119242

Your button view should have internal constraints, based on the label and the image. These should be sufficient to give it the correct size. You don't need to implement intrinsicContentSize for that.

The button's superview does not and should not know or care what is going on inside the button. You don't directly reference the intrinsic content size, the layout system does, and if your button has the right internal constraints, it isn't necessary.

Intrinsic content size is there to allow a view to express its size as something at the very bottom of the view hierarchy, based on its display contents, such as the text in a label. Everything above that is based on constraints.

You can also use it to allow a view with non-autolayout subviews to participate in autolayout, but this can lead to a lot of duplicated frame calculation code.

Upvotes: 2

Related Questions