1

我正在玩 AutoLayout 并且真的把我的头撞到墙上,因为它看起来应该是一个非常简单的解决方案。

  1. 我有一个垂直的控件列:1 个标签和 3 个按钮。
  2. 我希望标签的高度为 40 像素(点),并根据其超级视图的宽度(左侧、顶部和右侧的标准间距)自动调整其宽度。
  3. 我希望 3 个按钮在该标签下方垂直排列。
  4. 我希望它们的宽度像标签一样自动调整大小。
  5. 我希望它们的间距是标准的(水色?)间距(8 点,对吗?)。
  6. 我希望 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 的一些基本知识,或者它的功能是否需要如此复杂?

4

1 回答 1

7

您遇到错误是因为您将代码中生成的约束与界面生成器添加的约束混合和匹配。界面生成器不允许您生成模棱两可的布局,因此几乎按照定义,如果您添加额外的约束,您将得到一个"Unable to simultaneously satisfy"错误,这是许多婚姻的失败。

要解决这个问题,您要么需要在界面生成器中定义所有需要的约束,要么需要将特定的约束标记为出口并在代码中删除它们,然后再添加自己的。

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

您可以在选择标签时使用 IB 中的此按钮固定到特定高度:

在此处输入图像描述

中间的那个,看起来像一个大梁。这为您提供了以下有用的菜单:

在此处输入图像描述

选择其中一个允许您针对标签创建一个新的约束,然后您可以通过选择它来编辑它:

在此处输入图像描述

然后,您可以添加按钮,选择所有三个按钮,并使用相同的菜单创建等高约束。

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

于 2012-11-16T19:03:15.050 回答