参考文章:
约束的高级用法
注意点
深入了解Masonry有不懂的地方可以先看这篇文章,很全面
一些要注意的点
- 使用 mas_makeConstraints方法的元素必须事先添加到父元素中,例如[self.view addSubview:view];
- 通过storyBoard中拉出来的控件,想要用Masonry的话要先把这个view的AutoLayout选项去掉,否则会造成约束冲突(具体机制还不是很清楚,为什么即使没对控件设置约束,拉出来的控件还是有约束?是只要开启就有默认的约束吗?)
- 使用Masonry的时候不用设置
translatesAutoresizingMaskIntoConstraints
属性为NO; - masequalTo 和 equalTo 区别:masequalTo 比equalTo多了类型转换操作,一般来说,大多数时候两个方法都是 通用的,但是对于数值元素使用mas_equalTo。对于对象或是多个属性的处理,使用equalTo。特别是多个属性时,必须使用equalTo,例如 make.left.and.right.equalTo(self.view);
- 注意到方法with和and,这连个方法其实没有做任何操作,方法只是返回对象本身,这个方法的作用是为了提高可读性
make.left.and.right.equalTo(self.view);
和make.left.right.equalTo(self.view);
是完全一样的,但是明显的加了and方法的语句可读性更好点。 - left、right 和leftMargin、rightMargin 是不一样的,带margin的他默认会有layoutMargin,值为8;
- 简略写法
// 只要添加了这个宏,就不用带mas_前缀
#define MAS_SHORTHAND3
// 只要添加了这个宏,equalTo就等价于mas_equalTo
#define MAS_SHORTHAND_GLOBALS
// 这个头文件一定要放在上面两个宏的后面
#import "Masonry.h"
一、基本使用
1、 首先在Masonry中能够添加约束的有三个函
- (NSArray *)mas_makeConstraints:(void(^)(MASConstraintMaker *make))block;
- (NSArray *)mas_updateConstraints:(void(^)(MASConstraintMaker *make))block;
- (NSArray *)mas_remakeConstraints:(void(^)(MASConstraintMaker *make))block;
mas_makeConstraints 只负责新增约束,不能同时存在两条针对于同一对象的约束 否则会报错
mas_updateConstraints 针对上面的情况会更新在block中出现的约束,不会导致出现两个相同约束的情况
mas_remakeConstraints 则会清除之前的所有约束,仅保留最新的约束
- (void)mas_distributeViewsAlongAxis:(MASAxisType)axisType withFixedSpacing:(CGFloat)fixedSpacing leadSpacing:(CGFloat)leadSpacing tailSpacing:(CGFloat)tailSpacing;
这个方法是NSArray的一个扩展方法,用来对array里面的view进行布局,可以设置方向,间隔,距离父视图边缘的距离。
- (void)mas_distributeViewsAlongAxis:(MASAxisType)axisType withFixedItemLength:(CGFloat)fixedItemLength leadSpacing:(CGFloat)leadSpacing tailSpacing:(CGFloat)tailSpacing;
这个方法同上,只是设置的参数不同
使用例子:
[viewArr mas_distributeViewsAlongAxis:MASAxisTypeHorizontal
withFixedSpacing:5 leadSpacing:5 tailSpacing:5];
[viewArr mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(@60);
make.height.equalTo(@60);
}];
可以看到,除了调用 mas_distributeViewsAlongAxis:
方法外,还要调用 mas_makeConstraints
方法,这样才能确定这几个视图的位置。
2、 常用的支持属性
@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;
使用实践:
4.22
基本使用掌握的差不多,但是到具体的适配时感觉经验还是不足,还是要多看看别人的适配方法。
5.11
使用Masonry 时最好把view 的autoLayouta给关掉,不然可能会报很多冲突。
5.13
在使用约束时,如果受约束的控件有子控件,更新完约束后,有时其子控件的位置不会更新。(EJTextField)