Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autolayout height equal to MAX(multiple view heights)

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?

like image 230
Snowman Avatar asked Jun 14 '13 21:06

Snowman


People also ask

What is multiplier in Autolayout?

Multiplier is there for creating Proportional Constraint. Auto Layout calculates the first item's attribute to be the product of the second item's attribute and this multiplier . Any value other than 1 creates a proportional constraint.

What is intrinsic content size?

Intrinsic content size is information that a view has about how big it should be based on what it displays. For example, a label's intrinsic content size is based on how much text it is displaying. In your case, the image view's intrinsic content size is the size of the image that you selected.

How does a view's intrinsic content size aid in Auto layout?

In general, the intrinsic content size simplifies the layout, reducing the number of constraints you need. However, using the intrinsic content size often requires setting the view's content-hugging and compression-resistance (CHCR) priorities, which can add additional complications.


1 Answers

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.

like image 175
rob mayoff Avatar answered Oct 14 '22 17:10

rob mayoff