iOS Masonry详解
Masonry为简便控件布局的第三方框架
Masonry基础API
mas_makeConstraints() 添加约束
mas_remakeConstraints() 移除之前的约束,重新添加新的约束
mas_updateConstraints() 更新约束,写哪条更新哪条,其他约束不变
equalTo() 参数是对象类型,一般是视图对象或者mas_width这样的坐标系对象
mas_equalTo() 和上面功能相同,参数可以传递基础数据类型对象,可以理解为比上面的API更强大
width() 用来表示宽度,例如代表view的宽度
mas_width() 用来获取宽度的值。和上面的区别在于,一个代表某个坐标系对象,一个用来获取坐标系对象的值
equalTo():仅支持基本类型
mas-equalTo():支持类型转换,支持复杂类型,是对equalTo的分装
跟新约束和布局
- (void)updateConstraintsIfNeeded 调用此方法,如果有标记为需要重新布局的约束,则立即进行重新布局,内部会调用updateConstraints方法
- (void)updateConstraints 重写此方法,内部实现自定义布局过程
- (BOOL)needsUpdateConstraints 当前是否需要重新布局,内部会判断当前有没有被标记的约束
- (void)setNeedsUpdateConstraints 标记需要进行重新布局
常用方法
设置内边距
/**
设置yellow视图和self.view等大,并且有10的内边距。
注意根据UIView的坐标系,下面right和bottom进行了取反。所以不能写成下面这样,否则right、bottom这两个方向会出现问题。
make.edges.equalTo(self.view).with.offset(10);
除了下面例子中的offset()方法,还有针对不同坐标系的centerOffset()、sizeOffset()、valueOffset()之类的方法。
*/
[self.yellowView mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(self.view).with.offset(10);
make.top.equalTo(self.view).with.offset(10);
make.right.equalTo(self.view).with.offset(-10);
make.bottom.equalTo(self.view).with.offset(-10);
}];
注意 上述代码中出现的 with :三方库讲解:Optional semantic property which has no effect but improves the readability of constraint
可选语义属性,该属性没有影响,但提高了约束的可读性
相关属性
@property (nonatomic, strong, readonly) MASConstraint *left; // 左侧
@property (nonatomic, strong, readonly) MASConstraint *top; // 上侧
@property (nonatomic, strong, readonly) MASConstraint *right; // 右侧
@property (nonatomic, strong, readonly) MASConstraint *bottom; // 下册
@property (nonatomic, strong, readonly) MASConstraint *leading; // 首部
@property (nonatomic, strong, readonly) MASConstraint *trailing; // 尾部
@property (nonatomic, strong, readonly) MASConstraint *width; // 宽
@property (nonatomic, strong, readonly) MASConstraint *height; // 高
@property (nonatomic, strong, readonly) MASConstraint *centerX; // 横向中点
@property (nonatomic, strong, readonly) MASConstraint *centerY; // 纵向中点
@property (nonatomic, strong, readonly) MASConstraint *baseline; // 文本基线
@property (nonatomic, strong, readonly) MASConstraint *edges; // 内边距
@property (nonatomic, strong, readonly) MASConstraint *size; // 尺寸
@property (nonatomic, strong, readonly) MASConstraint *center; // 中点
部分控件在设置位置的时候,不需要设置控件的宽高,除非有特定需要。
控件的定位必须要使他一个角固定位置,否则会出现错误。