Masonry学习之链式属性

来源:互联网 发布:合金装备 mac 汉化 编辑:程序博客网 时间:2024/06/06 16:29

在前面的Masonry基本布局中,我们完成了绿、红和蓝三个视图的布局,Masonry的基本布局操作方式大大简化了苹果原生的自动布局代码。然而,我们还可以更进一步,这就是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);    }];

我们仔细观察发现,对于绿色视图而言,其top、left属性是有一些共同点的,都是相对于superview,偏移也相等,这种情况下,我们就可以使用链式属性的写法:

// chain attributesmake.top.and.left.equalTo(superview).insets(padding);// which is the equivalent of// make.top.greaterThanOrEqualTo(superview).insets(padding);// make.left.greaterThanOrEqualTo(superview).insets(padding);

同理,对于红色视图:

基本写法:

[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    }];

链式写法:

// chain attributesmake.top.and.right.equalTo(superview).insets(padding);

注意,基本写法中使用的offset有正负的区别,而链式写法中的insets使用的是绝对值,这也简化了理解。

同理,对于蓝色视图:
基本写法:

[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    }];

链式写法:

[blueView mas_makeConstraints:^(MASConstraintMaker *make) {        make.top.equalTo(greenView.mas_bottom).insets(padding);        // chain attributes        make.left.right.and.bottom.equalTo(superview).insets(padding);        make.height.equalTo(@[greenView, redView]);    }];

链式属性写法不仅精简了代码,更简化了语义,非常好用。

原创粉丝点击