我正在玩 AutoLayout 并且真的把我的头撞到墙上,因为它看起来应该是一个非常简单的解决方案。
- 我有一个垂直的控件列:1 个标签和 3 个按钮。
- 我希望标签的高度为 40 像素(点),并根据其超级视图的宽度(左侧、顶部和右侧的标准间距)自动调整其宽度。
- 我希望 3 个按钮在该标签下方垂直排列。
- 我希望它们的宽度像标签一样自动调整大小。
- 我希望它们的间距是标准的(水色?)间距(8 点,对吗?)。
- 我希望 3 个按钮的高度相同。
我可以得到我想要的工作,但我在运行时不断在控制台中收到错误,我想弄清楚为什么我得到它们以及如何避免得到它们。我在 AutoLayout 上观看了 WWDC 视频,这是我迄今为止尝试过的:
UILabel *label = [self Label];
MMGlossyButton *button1 = ...
MMGlossyButton *button2 = ...
MMGlossyButton *button3 = ...
[[self view] addConstraints:
[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[label]-|"
options:0
metrics:nil
views:NSDictionaryOfVariableBindings(label)]];
[[self view] addConstraints:
[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[button1]-|"
options:0
metrics:nil
views:NSDictionaryOfVariableBindings(new)]];
[[self view] addConstraints:
[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[button2]-|"
options:0
metrics:nil
views:NSDictionaryOfVariableBindings(existing)]];
[[self view] addConstraints:
[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[button3]-|"
options:0
metrics:nil
views:NSDictionaryOfVariableBindings(provider)]];
[[self view] addConstraints:
[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-[label(40)]-[button1(>=25)]-[button2(==button1)]-[button3(==button1)]-|"
options:0
metrics:nil
views:NSDictionaryOfVariableBindings(label, button1, button2, button3)]];
因此,这适用于以动态大小的方式显示视图,但控制台中会弹出以下错误:
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)
// A whole bunch of constraint stuff that doesn't appear to be important...
Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x7554c40 V:[MMGlossyButton:0x7554b40(99)]>
所以,最后一点似乎表明我在视图上的第一个按钮静态大小为 99 磅高。
这是它在视图上的大小。
这是完全任意的。
我不想分配,但无法找到取消分配的方法。
尽管我得到了我想要的东西(某种程度上,最终),但这似乎是一种真正迂回的方式来完成非常简单的事情。我是否缺少有关 AutoLayout 的一些基本知识,或者它的功能是否需要如此复杂?