OC:Masonry约束冲突

说明
首次发布 2017年06月01日
最近更新 2018年03月24日

代码示例:

#import "ViewController.h"

// Libs
#import "Masonry.h"

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIView *redView = [[UIView alloc] init];
    redView.mas_key = @"redView";
    redView.backgroundColor = [UIColor redColor];
    
    UIView *blueView = [[UIView alloc] init];
    blueView.mas_key = @"blueView";
    blueView.backgroundColor = [UIColor blueColor];
    
    [self.view addSubview:redView];
    [self.view addSubview:blueView];
    
    [redView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@10);
        make.height.equalTo(@50);
        make.right.equalTo(blueView.mas_left);
        // 冲突
        make.width.equalTo(@120);
        make.top.equalTo(@50);
    }];
    
    [blueView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(@-30);
        make.height.top.equalTo(redView);
        // 冲突
        make.width.equalTo(@50);
    }];
}

@end

控制台输出:(忽略无用输出)

[LayoutConstraints] 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. 
(
    "<MASLayoutConstraint:0x283d8d380 UIView:redView.left == UIView:0x100a0e440.left + 10>",
    "<MASLayoutConstraint:0x283d8d6e0 UIView:redView.right == UIView:blueView.left>",
    "<MASLayoutConstraint:0x283d8d800 UIView:redView.width == 120>",
    "<MASLayoutConstraint:0x283d8daa0 UIView:blueView.right == UIView:0x100a0e440.right - 30>",
    "<MASLayoutConstraint:0x283d8dd40 UIView:blueView.width == 50>",
    "<NSLayoutConstraint:0x283a9a530 UIView:0x100a0e440.width == 375>"
)

Will attempt to recover by breaking constraint 
<MASLayoutConstraint:0x283d8d800 UIView:redView.width == 120>

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKitCore/UIView.h> may also be helpful.

现在就可以很清楚地看到,冲突为:

<MASLayoutConstraint:0x283d8d800 UIView:redView.width == 120>


拓展

顺便说一下,对于代码写的高度自适应的 cell,会有提示 <NSLayoutConstraint:UITableViewCellContentView:.height == 44>。这个并不是说一定是你布局的问题。而是系统在 cell 还没有展示出来计算高度的时候,直接返回了44的约束,当cell添加上view上之后,发生约束冲突。解决也很简单,就是再垂直方向添加一个.priorityHigh(),来提高优先级。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容