iOS:带有1个标签和3个button的简单AutoLayout

我正在玩AutoLayout,真的把我的头撞在墙上,看起来应该是一个非常简单的解决scheme。

  1. 我有一个垂直的控件列:1个标签和3个button。
  2. 我希望标签的高度是40像素(点),并根据其超视图的宽度(左侧,顶部和右侧的标准间距)自动调整宽度。
  3. 我想要3个button在该标签下方垂直排列。
  4. 我想他们的宽度自动resize就像标签。
  5. 我想他们的间距是标准的(aqua?)间距(8分,对吧?)。
  6. 我想3个button是相同的高度。

我可以得到我想要的工作,但是我一直在运行时在控制台中出现错误,我想弄清楚为什么我要得到它们,以及如何避免得到它们。 我已经观看了AutoLayout上的WWDCvideo,以下是我到目前为止所尝试的:

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)]]; 

因此,这适用于以dynamic大小的方式显示视图,但在控制台中popup以下错误消息:

 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)]> 

所以,最后一位似乎表明,我在视图上的第一个button是静态大小高达99点。
视图上的大小是多less?
这是完全武断的。
我不想分配它,但不能找出一个方法来取消分配它。

虽然我得到了我想要的东西(最终),但它似乎是一个非常简单的迂回方式。 我是否缺less一些关于AutoLayout的基本知识,或者它的能力是否需要如此复杂?

您正在遇到错误,因为您正在混合和匹配由代码生成的约束以及由接口生成器添加的约束。 界面生成器不会让你生成一个模糊的布局,所以几乎按照定义,如果你添加额外的约束,你会得到一个"Unable to simultaneously satisfy"错误,这是许多婚姻的垮台。

要解决这个问题,您需要在界面构build器中定义所有您需要的约束,或者您需要将特定的约束标记为出口,并在添加自己的代码之前将其删除。

在你的情况下,约束很简单,可以在IB中创build。

在您select标签的情况下,您可以使用IB中的此button将其固定到特定的高度:

在这里输入图像说明

中间那个,看起来像一个大梁。 这给你以下有用的菜单:

在这里输入图像说明

select其中之一可以让您为标签创build一个新的约束,您可以通过select它来进行编辑:

在这里输入图像说明

然后,您可以添加button,select所有三个button,并使用相同的菜单创build一个相等的高度限制。

在IB中创build的约束不是特别灵活,所以如果您确定需要在代码中创build或修改它们,则最好创build出口到特定约束,然后删除并重新创build它们,或者修改在运行时constant值。