我有一系列这样堆叠的 View
________________
| |
| View 1 |
|________________|
| |
| View 2 |
|________________|
| |
| View 3 |
|________________|
这些 View 可以展开和折叠,因此如果 View 1 展开, View 2 的顶部和底部将位于 View 1 的顶部,与 View 2 相关的 View 3 的顶部和底部也是如此。
________________
| |
| View 1 |
| |
| |
| |
|________________|
| |
| View 2 |
|________________|
| |
| View 3 |
|________________|
________________
| |
| View 1 |
|________________|
| |
| View 2 |
| |
| |
| |
|________________|
| |
| View 3 |
|________________|
我无法通过 IB 添加这些 View ,因为这个布局是动态创建的,所以我也必须通过代码和约束添加 View 。
我正在做这个
UIView *previousView = nil;
for (UIView *view in views) {
if (previousView) {
NSArray *constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:[previousView][view]"
options:0
metrics:nil
views:NSDictionaryOfVariableBindings(previousView, view)];
[superview addConstraints:constraints];
}
}
当我点击 View 将其展开时,我收到错误
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. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints)
(
"<NSAutoresizingMaskLayoutConstraint:0x76407b0 h=&-& v=--& V:[MyView:0x764c0f0(44)]>",
"<NSAutoresizingMaskLayoutConstraint:0x763e370 h=&-& v=--& V:[MyView:0x7646490(44)]>",
"<NSLayoutConstraint:0x76440d0 V:[MyView:0x764c0f0]-(0)-[MyView:0x7648eb0]>",
"<NSLayoutConstraint:0x7643920 V:[MyView:0x7648eb0]-(0)-[MyView:0x7646490]>",
"<NSAutoresizingMaskLayoutConstraint:0x76407f0 h=&-& v=--& MyView:0x764c0f0.midY == + 22>",
"<NSAutoresizingMaskLayoutConstraint:0x76d9ea0 h=&-& v=--& MyView:0x7648eb0.midY == + 91.5>",
"<NSAutoresizingMaskLayoutConstraint:0x763e3b0 h=&-& v=--& MyView:0x7646490.midY == + 110>"
)
Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x7643920 V:[MyView:0x7648eb0]-(0)-[MyView:0x7646490]>
显然我做错了。我是否必须将 setTranslatesAutoresizingMaskIntoConstraints
设置为 NO
并向定位添加我自己的约束?或者问题是我在该循环上添加的约束?
最佳答案
如何更改 View 的大小?您有一个约束将两个 View 之间的垂直空间固定为 0。您收到的错误是否显示任何其他约束(可能是您没有显式添加的约束)?我怀疑 View 2 和/或 View 3 可能存在另一个约束,不允许它们向下移动以满足 V-[View 1]-(0)-[View 2]
约束.
如果不涉及其他约束,只需更改要展开或折叠的 View 的高度即可。
如 Apple documentation 中所述如果您自己设置所有约束,您可能应该调用 setTranslatesAutoresizingMaskIntoConstraints:NO
否则您的显式约束将与隐式添加的自动调整大小蒙版约束发生冲突,这看起来就像在本例中发生的情况。
编辑:在看到上面列出的所有限制的编辑后,它证实了我的意思。通过翻译自动调整大小蒙版添加的约束与您的自动布局约束冲突。他们明确固定每个 View 相对于父 View 的中心 Y 位置。尝试 setTranslatesAutoresizingMaskIntoConstraints:NO
并根据需要设置您需要的任何其他约束。
关于ios - 使用自动布局制作动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17271177/