问题描述
目前我在1个视图中有3个视图(固定在superview的前缘和后缘)。
3个观点目前看起来像这样:
如何通过自动布局实现此目的?或者我如何使用IBOutlets实现约束?
Tj3n的答案有效,但它有一个缺点,你必须使用代码中的幻数,并在代码和IB中设置constrant属性。
恕我直言,一个更好的解决方案是设置IB中具有不同优先级的所有约束并激活/在代码中停用它们。试试这个:
- 像以前一样设置前导/尾随约束。
- 设置等宽所有三个视图的约束优先级
高
。 - 为所有三个视图设置0宽度约束,优先级为
IBOutlet
,就像连接视图一样。 - 激活任何0宽度约束以折叠您想要的视图,然后停用它们进行扩展。
请注意,只有1和2就位,可以实现等宽视图布局。使用3和4,您可以选择性地折叠/展开任何视图。
Currently I have 3 views inside 1 view (which is pinned to leading edge and trailing edge of superview).
The 3 views look like this currently:
However, in some cases, I wish to hide the indigo view, but still keep the last 2 the same widths like so:
How can I achieve this with autolayout? Or how can I achieve this using IBOutlets for constraints?
Tj3n's answer works, but it has a drawback that you have to use magic numbers in your code and set constrant properties both in code and IB.
IMHO, a better solution would be setting up all the constrants in IB with different priorities and activating/deactivating them in code. Try this:
- Set the leading/trailing constraints as you did before.
- Set equal width constraints for all three views with priority
high
. - Set 0 width constraints for all three views with priority
required
, but leave them deactivated in IB. And connect them toIBOutlet
s in code just as connecting views. - Activate any of the 0 width constraints to collapse the view you want, and later deactivate them to expand.
Note that just with 1 and 2 in place, you can achieve the equal-width view layout. And with 3 and 4, you can collapse/expand any of the views selectively.
这篇关于自动布局如何在具有3个相等宽度视图的视图中隐藏1个视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!