28

Say I have a view called container. container contains 5 UIButtons. I want to add a height NSLayoutConstraint on container, and this height should be equal to the NSLayoutHeightAttribute of the tallest button in its subviews.

I don't see a straightforward way to do this. Anyone have any ideas?

1 Answer 1

40

You need one constraint for each subview (button), specifying that the container's height should be greater than or equal to the subview's height. Give that constraint a high priority, like UILayoutPriorityRequired (which is the default anyway).

Then add one more constraint on the container's height, specifying that it should have a height equal to zero. Give that constraint a low priority, like UILayoutPriorityLow. Since auto layout tries to minimize the error of unsatisfied constraints, it will make the container as short as possible while still satisfying all higher-priority constraints.

I have put an example in this gist. It produces this result:

example screen shot

The blue views have fixed heights. The tan view is the superview of the blue views and its height is constrained as I described above. I pinned each subview's bottom to the container's bottom, but you could pin the tops or the Y centers instead.

3
  • Awesome, this worked. Though I'm a bit confused. We're allowed to add multiple height constraints on the container? If I say the container's height should be greater than equal to subview1, and also subview2, why do those two not conflict? Also, I don't understand your reasoning behind the last low priority constraint. I tried without it and that also worked. Is that a safety measure?
    – Snowman
    Jun 18, 2013 at 16:27
  • 1
    If there as a layout that satisfies both constraints, then the constraints don't conflict. Indeed, the definition of conflicting constraints is that they can't both be satisfied simultaneously. Suppose your subviews have heights 60, 80, and 100. Then any container height of 100 or more can satisfy the constraints between the subview heights and the container height, so the constraints aren't in conflict with each other.
    – rob mayoff
    Jun 18, 2013 at 16:46
  • Since any container height at least 100 will satisfy the constraints from the subviews I just described, those constraints by themselves are ambiguous: there are multiple satisfactory solutions. Auto layout doesn't complain about ambiguity, and may give you the layout you want. But some change to your app or to iOS might make auto layout give a layout you don't want in the future. The extra, low-priority constraint protects you from that.
    – rob mayoff
    Jun 18, 2013 at 17:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.