Masonry学习之基本布局

来源:互联网 发布:c语言ide 编辑:程序博客网 时间:2024/06/16 13:48

何谓基本布局?个人以为即确定的一个或几个视图,设置固定的约束,约束不会发生更新和变化。
此处一例,来自Masonry官方例子,如下图所示:

这里写图片描述

如果使用苹果原生的纯代码相对布局来添加约束,需要添加15条约束,约束的逻辑并不复杂,无非上下左右、等宽和等高,但是代码却十分繁琐,多达100多行。有兴趣可以自己写写看,尤其初学的话,最好动动手。

那我们使用Masonry实现同样的约束布局又是怎样的呢?看代码:

[greenView makeConstraints:^(MASConstraintMaker *make) {        make.top.greaterThanOrEqualTo(superview.top).offset(padding);        make.left.equalTo(superview.left).offset(padding);        make.bottom.equalTo(blueView.top).offset(-padding);        make.right.equalTo(redView.left).offset(-padding);        make.width.equalTo(redView.width);        make.height.equalTo(redView.height);        make.height.equalTo(blueView.height);    }];    //with is semantic and option    [redView mas_makeConstraints:^(MASConstraintMaker *make) {        make.top.equalTo(superview.mas_top).with.offset(padding); //with with        make.left.equalTo(greenView.mas_right).offset(padding); //without with        make.bottom.equalTo(blueView.mas_top).offset(-padding);        make.right.equalTo(superview.mas_right).offset(-padding);        make.width.equalTo(greenView.mas_width);        make.height.equalTo(@[greenView, blueView]); //can pass array of views    }];    [blueView mas_makeConstraints:^(MASConstraintMaker *make) {        make.top.equalTo(greenView.mas_bottom).offset(padding);        make.left.equalTo(superview.mas_left).offset(padding);        make.bottom.equalTo(superview.mas_bottom).offset(-padding);        make.right.equalTo(superview.mas_right).offset(-padding);        make.height.equalTo(@[greenView.mas_height, redView.mas_height]); //can pass array of attributes    }];

官方示例代码原封不动,三十多行。更值得关注的是其近乎自然语言的可读性:

make.top.greaterThanOrEqualTo(superview.top).offset(padding);

这句代码翻译过来就是:make这个约束的top大于或等于superview的top,偏移padding距离。太直白了。