dev

Self sizing UIViews with AutoLayout

Simulator Screen Shot - iPod touch (7th generation) - 2020-10-15 at 10.34.07.png

Let’s say you have 3 views.

You want to pin the TopView to the top of the screen, the MiddleView to the TopView, and the BottomView to the MiddleView.

The MiddleView is a custom view with 2 subviews, one of which has a variable height based on the content.

My old understanding is that I needed to properly set the intrinsicContentSize of my custom MiddleView for AutoLayout to do its job.

There’s a bunch of hacks online to calculate the size of the text and then tell AutoLayout to make another pass at laying it out. But that’s a lot of work and unnecessary.

The simple answer is to make sure your custom, dynamically sized view also pins to its bottom.

I mistakenly didn’t want AutoLayout to constrain the height of my label. Dummy. AutoLayout is smart enough to use that bottom-pin to calculate how far away from the bottom you want to be, which informs its final size-calculation.

Here’s some sample code for the dynamic-height layout.