masnory初级用法
Masonry 的下载地址: https://github.com/SnapKit/Masonry
- 约束的三个函数
//这个方法只会添加新的约束
[blueView mas_makeConstraints:^(MASConstraintMaker *make) {
}];
// 这个方法会将以前的所有约束删掉,添加新的约束
[blueView mas_remakeConstraints:^(MASConstraintMaker *make) {
}];
// 这个方法将会覆盖以前的某些特定的约束
[blueView mas_updateConstraints:^(MASConstraintMaker *make) {
}];
- 常用的约束各种类型
/**
1.尺寸:width、height、size
2.边界:left、leading、right、trailing、top、bottom
3.中心点:center、centerX、centerY
4.边界:edges
5.偏移量:offset、insets、sizeOffset、centerOffset
6.priority()约束优先级(0~1000),multipler乘因数, dividedBy除因数
*/
例如添加一个距离父view边距为20的view,看我是怎么甩掉frame的
UIView *fatherView = [[UIView alloc]init];
[fatherView setBackgroundColor:[UIColor grayColor]];
[self.view addSubview:fatherView];
[fatherView mas_makeConstraints:^(MASConstraintMaker *make){
make.edges.insets(UIEdgeInsetsMake(20, 20, 20, 20));
}];
1-5大家都很好理解是吧,我主要记录一下6的用法
//对于橙色View只需正常设置约束就好
[self.orangeView mas_makeConstraints:^(MASConstraintMaker *make) {
make.width.height.mas_equalTo(100);
make.left.offset(10);
make.top.offset(50);
}];
//黄色View只会发生一次变化,就多设一个优先级较低的约束就好
[self.yellowView mas_makeConstraints:^(MASConstraintMaker *make) {
make.width.height.mas_equalTo(100);
make.left.equalTo(self.orangeView.mas_right).offset(20);
make.top.offset(50);
//当橙色View消失后,黄色View缺少左边约束,所以给其加一个优先级更低的左边约束。当第一个左边约束失效后,这个约束就起作用了
make.left.equalTo(self.view.mas_left).offset(20).priority(300);
}];
//同理绿色View的低级约束就得设置两个
[self.greenView mas_makeConstraints:^(MASConstraintMaker *make) {
make.width.height.mas_equalTo(100);
make.left.equalTo(self.yellowView.mas_right).offset(20);
make.top.offset(50);
make.left.equalTo(self.orangeView.mas_right).offset(20).priority(300);
make.left.equalTo(self.view.mas_left).offset(20).priority(250);
}];
}
//两个按钮事件remove
- 更多的约束条件
//使得宽度和高度大于等于
make.size.greaterThanOrEqualTo(redView);
//还可以这么写,除了top,所有边界和superview对齐
make.left.right.and.bottom.equalTo(superview);
make.top.equalTo(otherView);
- 更新约束
//1.告知需要更新约束,但不会立刻开始,系统然后调用updateConstraints
[self setNeedsUpdateConstraints];
//2.告知立刻更新约束,系统立即调用updateConstraints
[self updateConstraintsIfNeeded];
//3.这里动画当然可以取消,具体看项目的需求
//系统block内引用不会导致循环引用,block结束就会释放引用对象
[UIView animateWithDuration:0.4 animations:^{
[self layoutIfNeeded]; //告知页面立刻刷新,系统立即调用updateConstraints
}];
一般我使用layoutIfNeeded
欢迎一起来研究,QQ 253807688