【问题标题】:Autolayout constraint conflict when I specified just one constraint当我只指定一个约束时自动布局约束冲突
【发布时间】:2013-04-07 23:34:34
【问题描述】:

我的控制器中有以下简单的测试代码:

- (void)loadView
{
    UIView *view = [UIView new];
    [self setView:view];

    UILabel *label = [UILabel new];
    [label setText:@"Hello World!"];

    [view addSubview:label];

    [view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|-[label]"
        options:0 metrics:nil views:NSDictionaryOfVariableBindings(label)]];
} 

代码失败并出现以下异常,我不知道为什么。任何帮助将不胜感激:

2013-04-15 14:15:47.880 libmarkup-test[1072:c07] 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) 
(
    "<NSLayoutConstraint:0x753eb60 H:|-(NSSpace(20))-[UILabel:0x7536b60]   (Names: '|':UIView:0x75376a0 )>",
    "<NSAutoresizingMaskLayoutConstraint:0x712a2c0 h=--& v=--& UILabel:0x7536b60.midX ==>"
)

Will attempt to recover by breaking constraint 
<NSLayoutConstraint:0x753eb60 H:|-(NSSpace(20))-[UILabel:0x7536b60]   (Names: '|':UIView:0x75376a0 )>

Break on objc_exception_throw to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.

“无法同时满足约束”消息特别令人困惑,因为据我所知,我只指定了一个约束。

【问题讨论】:

  • 由于某种原因,问题在我写完之前就发布了。
  • Greg:你在哪里设置视图的框架?为什么要使用 setView?你想添加你正在创建的视图作为某个控制器的子视图吗?我不确定我们是否有足够的信息来帮助您。
  • 我没有设置视图的框架 - 我将它设置为我的控制器的视图。控制器调整其大小以填满屏幕。此代码正在 loadView 中执行。我在代码示例中添加了更多上下文。
  • 顺便说一句,如果我注释掉对 addConstraints:options:metrics:views: 的调用,而是直接设置 UILabel 的框架(例如 [label setFrame:CGRectMake(5, 10, 320, 20) ]),示例按预期工作。

标签: ios autolayout autoresizingmask


【解决方案1】:

您似乎忘记在 UILabel 上设置 translatesAutoresizingMaskIntoConstraints。默认情况下它将是 YES。因此,该标签上的自动调整大小掩码将转换为其他约束,然后与您指定的约束发生冲突。

添加这个应该可以解决约束问题:

label.translatesAutoresizingMaskIntoConstraints = NO;

您可能还应该考虑该标签上的垂直约束。

【讨论】:

  • 在“将尝试恢复...”之前和之后,您没有看到约束列表吗?您应该在该行之后至少看到一个,在该行之前至少看到两个。
  • 我愿意...不过,看起来编辑器将该部分视为标记,因此没有通过。我刚刚重新格式化了帖子,以便您可以看到它。
  • 这确实解决了问题 - 谢谢。然而,这有点令人惊讶。我不希望将该标志设置为 NO,因为我没有明确设置标签的自动调整大小掩码(根据文档,默认值为 UIViewAutoresizingNone)。有什么办法可以避免设置这个标志?
  • 完美。所以,是的,您可以看到以 &lt;NSAutoresizingMaskLayoutConstraint:0x712a2c0... 开头的约束与您创建的约束冲突。
  • 啊,我明白你的意思了。我之前没有注意到“NSAutoresizingMaskLayoutConstraint”文本。但是我仍然对为什么要应用它感到困惑,因为我还没有设置自动调整大小的蒙版。
【解决方案2】:

请调整约束优先级(默认为1000)和拥抱优先级(默认为250)

【讨论】:

  • 这个问题已经被正确回答了。问题是translatesAutoresizingMaskIntoConstraints 标志。它与内容优先级无关。
猜你喜欢
  • 2021-08-27
  • 2017-11-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多