公司一直用的代码(自己封装的一套约束工具)和xib(autoLayout)相结合的方式来对控件进行布局和约束。本人更倾向于用纯代码布局。虽然公司封装了一套代码布局的方法,但为了更好适应其它的工作,决定开始学习使用Masonry。并记录学习的心得,与大家共享。
一.基础篇
1.Masonry下载地址下载地址。也可以用cocoaPods来管理。
2.正式开始
在.pch文件添加以下代码
//define this constant if you want to use Masonry without the 'mas_' prefix
#define MAS_SHORTHAND//可不加mas前缀了
//define this constant if you want to enable auto-boxing for default syntax
#define MAS_SHORTHAND_GLOBALS //自动装箱
注意:添加Masonry约束前,要保证控件已经添加到父控件上了。
UIView *greenView = UIView.new;
greenView.backgroundColor = UIColor.greenColor;
greenView.layer.borderColor = UIColor.blackColor.CGColor;
greenView.layer.borderWidth = 2;
[self addSubview:greenView];
UIView *redView = UIView.new;
redView.backgroundColor = UIColor.redColor;
redView.layer.borderColor = UIColor.blackColor.CGColor;
redView.layer.borderWidth = 2;
[self addSubview:redView];
UIView *blueView = UIView.new;
blueView.backgroundColor = UIColor.blueColor;
blueView.layer.borderColor = UIColor.blackColor.CGColor;
blueView.layer.borderWidth = 2;
[self addSubview:blueView];
UIView *superview = self;
int padding = 10;
[greenView mas_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);
}];
[redView mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(superview.top).offset(padding);
make.left.equalTo(greenView.right).with.offset(padding);//可以加with,提高可读性
make.bottom.equalTo(blueView.top).offset(-padding);
make.right.equalTo(superview.right).offset(-padding);
make.width.equalTo(greenView);
make.height.equalTo(@[greenView,blueView]);//可以通过数组,里面是view
}];
[blueView mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(greenView.bottom).offset(padding);
make.left.equalTo(superview.left).offset(padding);
make.bottom.equalTo(superview.bottom).offset(-padding);
make.right.equalTo(superview.right).offset(-padding);
make.height.equalTo(@[greenView.mas_height,redView.mas_height]);
}];//通过数组,里面是属性
运行,就能看到上面的效果图了。这是最基本的Masonry用法。