自动布局高度等于MAX(多视图高度) [英] Autolayout height equal to MAX(multiple view heights)
问题描述
说我有一个视图叫做 container
。 container
包含5 UIButtons
。我想在 container
上添加一个高度 NSLayoutConstraint
,这个高度应该等于 NSLayoutHeightAttribute
其最高的按钮在其子视图。
我没有看到一个简单的方法来做到这一点。
每个子视图(按钮)需要一个约束,指定容器的高度应大于或等于子视图的高度。给这个约束一个高优先级,如 UILayoutPriorityRequired
(这是默认的)。
然后再添加一个约束对容器的高度,指定它应该具有等于零的高度。给这个约束一个低优先级,如 UILayoutPriorityLow
。由于自动布局试图最小化未满足的约束的错误,它将使容器尽可能短,同时仍然满足所有更高优先级的约束。
我举了一个例子在
蓝色视图固定高度。棕褐色视图是蓝色视图的superview,其高度受到约束,如上所述。我将每个子视图的底部固定在容器的底部,但您可以固定顶部或Y中心。
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?
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:
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.
这篇关于自动布局高度等于MAX(多视图高度)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!