Masonry是一个轻量级的OC布局框架, 拥有自己的描述语法,采用更优雅的链式语法封装自动布局,简洁明了,并具有高可读性,而且同时支持 iOS 和 Max OS X。
Masonry支持的属性与NSLayoutAttrubute的对照:
MASConstraint (Masonry) | NSAutoLayout | 说明 |
---|---|---|
left | NSLayoutAttributeLeft | 左侧 |
top | NSLayoutAttributeTop | 上侧 |
right | NSLayoutAttributeRight | 右侧 |
bottom | NSLayoutAttributeBottom | 下侧 |
leading | NSLayoutAttributeLeading | 首部 |
trailing | NSLayoutAttributeTrailing | 尾部 |
width | NSLayoutAttributeWidth | 宽 |
height | NSLayoutAttributeHeight | 高 |
centerX | NSLayoutAttributeCenterX | 横向中点 |
centerY | NSLayoutAttributeCenterY | 纵向中点 |
baseline | NSLayoutAttributeBaseline | 文本基线 |
其中leading与left, trailing与right 在正常情况下是等价的。但是当一些布局是从右至左时(比如阿拉伯文) 则会对调, 换句话说就是基本可以 用left和right就好了。
在Masonry中能够添加AutoLayout约束有三个函数:
1
2
3
4
5
6
7
8/*
mas_makeConstraints 只负责新增约束 Autolayout不能同时存在两条针对于同一对象的约束 否则会报错
mas_updateConstraints 针对上面的情况 会更新在block中出现的约束 不会导致出现两个相同约束的情况
mas_remakeConstraints 则会清除之前的所有约束 仅保留最新的约束
*/
- (NSArray *)mas_makeConstraints:(void(^)(MASConstraintMaker *make))block;
- (NSArray *)mas_updateConstraints:(void(^)(MASConstraintMaker *make))block;
- (NSArray *)mas_remakeConstraints:(void(^)(MASConstraintMaker *make))block;equalTo
和mas_equalTo
的区别?mas_equalTo
是宏,在MASConstraint.h
文件中定义:1
#define mas_equalTo(...) equalTo(MASBoxValue((__VA_ARGS__)))
mas_equalTo 比equalTo多了类型转换操作, 大多数时候两个方法都是 通用的,但是对于数值元素使用mas_equalTo。对于对象或是多个属性的处理,使用equalTo。
以几个🌰学习Masonry:
1 中心点与self.view相同,宽度为300*300
1 | // exp1: 中心点与self.view相同,宽度为300*300 |
2 上下左右边距都为10
1 | -(void)exp2 { |
- edges 就是top,left,bottom,right简化写法
- 写法2中 bottom和right的offset是负数,因为计算的是绝对的数值,也就是view的bottom的y值减去self.view的bottom的y值是-10,view的right的x值减去self.view的right的x值是-10。
and
和with
什么事件都没做,只是从应用语法看上去很顺。
3 让两个高度为150的view垂直居中且等宽且等间隔排列 间隔为10(自动计算器高度)
1 | -(void)exp3{ |
4 iOS自带计算器布局
1 | -(void)exp4{ |
代码: MasonryDemo