所以,你有这个:
问题是,当你第一次折叠内部堆栈时,你会得到自动布局错误:
2017-07-02 15:40:02.377297-0500 nestedStackViews[17331:1727436] [LayoutConstraints] Unable to simultaneously satisfy constraints.
Probably at least one of the constraints in the following list is one you don't want.
Try this:
(1) look at each constraint and try to figure out which you don't expect;
(2) find the code that added the unwanted constraint or constraints and fix it.
(
"<NSLayoutConstraint:0x62800008ce90 'UISV-canvas-connection' UIStackView:0x7fa57a70fce0.top == UILabel:0x7fa57a70ffb0'Top Label of Inner Stack'.top (active)>",
"<NSLayoutConstraint:0x62800008cf30 'UISV-canvas-connection' V:[UILabel:0x7fa57d30def0'Bottom Label of Inner Sta...']-(0)-| (active, names: '|':UIStackView:0x7fa57a70fce0 )>",
"<NSLayoutConstraint:0x62000008bc70 'UISV-hiding' UIStackView:0x7fa57a70fce0.height == 0 (active)>",
"<NSLayoutConstraint:0x62800008cf80 'UISV-spacing' V:[UILabel:0x7fa57a70ffb0'Top Label of Inner Stack']-(8)-[UILabel:0x7fa57d30def0'Bottom Label of Inner Sta...'] (active)>"
)
Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x62800008cf80 'UISV-spacing' V:[UILabel:0x7fa57a70ffb0'Top Label of Inner Stack']-(8)-[UILabel:0x7fa57d30def0'Bottom Label of Inner Sta...'] (active)>
Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.
正如您所指出的,问题在于外部堆栈视图将高度 = 0 约束应用于内部堆栈视图。这与内部堆栈视图在其自己的子视图之间应用的 8 点填充约束相冲突。两个约束不能同时满足。
我相信,外部堆栈视图使用这个 height = 0 约束,因为它在动画时看起来比只隐藏内部视图而不先收缩更好。
对此有一个简单的解决方法:将内部堆栈视图包装在一个 plainUIView
中,并隐藏该包装器。我会示范。
这是上面损坏版本的场景大纲:
要解决此问题,请选择内部堆栈视图。从菜单栏中,选择编辑器 > 嵌入 > 视图:
当我这样做时,Interface Builder 在包装视图上创建了一个宽度约束,因此删除该宽度约束:
接下来,在包装器的所有四个边缘和内部堆栈视图之间创建约束:
此时,布局在运行时实际上是正确的,但 Interface Builder 绘制不正确。您可以通过将内部堆栈的孩子的垂直拥抱优先级设置得更高来解决它。我将它们设置为 800:
在这一点上,我们实际上还没有解决不可满足的约束问题。为此,请找到您刚刚创建的底部约束并将其优先级设置为低于要求。让我们将其更改为 800:
最后,您可能在视图控制器中有一个连接到内部堆栈视图的插座,因为您正在更改它的hidden
属性。更改该出口以连接到包装器视图而不是内部堆栈视图。如果您的插座类型是UIStackView
,您需要将其更改为UIView
。我的已经是 type 了UIView
,所以我只是在情节提要中重新连接了它:
Now, when you toggle the wrapper view's hidden
property, the stack view will appear to collapse, with no unsatisfiable constraint warnings. It looks virtually identical, so I won't bother posting another GIF of the app running.
You can find my test project in this github repository.