Luke
Luke

Reputation: 9690

Automatically set height of custom UIView based on its contents?

I’ve taken a lot of time to read other questions before asking this one, and haven’t managed to solve the issue yet – hopefully someone can help.

I have a custom alert view, a UIView subclass. I’m trying to get it into a state where its width is fixed, and its height grows dynamically based on the height of its two labels (title and message), and a dynamic number of action buttons it can be set up with.

I’ve used AutoLayout to set up the controls, which is working fine, but for now I’m still manually setting the frame of the view itself in its initialiser.

What I need to do is have the view’s height be calculated by the height of my two labels, and n buttons, plus the spacing between them.

I’ve tried providing an intrinsicContentSize for my view, but that method is never called, and it doesn’t even ask for it, so I’m stumped as to how to proceed.

To summarise: I probably need iOS9’s UIStackView, but I don’t have that luxury, so I need to bake something similar into iOS 7 / 8. I’ve looked at OAStackView but I’d rather not use an external dependency.

Upvotes: 2

Views: 1161

Answers (1)

JWKot
JWKot

Reputation: 360

Just a quick thought: Have you tried to create the view in Interface Builder? Give it a fixed width with Priority: 1000. Add no Height constraint but center the view vertically in its superview.

Then set the View's vertical content hugging priority and vertical content compression resistance priority to 1000.

This should cause the view to calculate its own height based on its subviews. You only need to make sure, that the subviews are bound to the superview in a way that defines the height without any ambiguity.

Upvotes: 4

Related Questions