2

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

- (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.

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

4

2 回答 2

8

看起来你忘记translatesAutoresizingMaskIntoConstraints在 UILabel 上设置了。默认情况下它将是 YES。因此,该标签上的自动调整大小掩码被转换为附加约束,然后与您指定的约束相冲突。

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

label.translatesAutoresizingMaskIntoConstraints = NO;

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

于 2013-04-15T19:34:40.840 回答
-1

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

于 2018-09-17T07:07:56.430 回答