1. 使用CocoaPods导入
$ pod 'MJRefresh'
2. 在项目中导入Masonry.h 文件
#import "Masonry.h"
3. 示例:有 blueview redview changebtn 三个控件,按如图1 排列
代码如下:
//Masonry的使用
主要用到 mas_makeConstraints / mas_remakeConstraints方法
**** 有一点需要注明,在使用masonry的方法前,一定要先把控件添加到父视图,不然会发生崩溃,提示找不到父视图!!!
blueview= [[UIViewalloc]init];
blueview.backgroundColor = [UIColor blueColor];
[self.view addSubview:blueview];
redview= [[UIViewalloc]init];
redview.backgroundColor = [UIColor redColor];
[self.view addSubview:redview];
UIButton* changebtn = [[UIButtonalloc]init];
changebtn.backgroundColor = [UIColor greenColor];
[self.view addSubview:changebtn];
[changebtnaddTarget:nil action:@selector(changePosition) forControlEvents:UIControlEventTouchUpInside];
//blueview的约束
[blueview mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(self.view).offset(20);
make.top.equalTo(self.view).offset(100);
make.right.equalTo(self.view).offset(-20);
make.height.equalTo(@50);
}];
//redview的约束
[redview mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(self->blueview.mas_centerX);
make.top.equalTo(self->blueview.mas_bottom).offset(20);
make.right.equalTo(self->blueview.mas_right);
make.height.equalTo(self->blueview.mas_height);
}];
//changebtn的约束
[changebtn mas_makeConstraints:^(MASConstraintMaker*make) {
make.top.equalTo(self->redview.mas_bottom).offset(60);
make.centerX.equalTo(self.view.mas_centerX);
make.height.equalTo(self->blueview.mas_height);
make.left.equalTo(self.view).offset(120);
}];
4. 若想通过点击按钮,改变blueview redview 的位置,添加事件
使用 mas_remakeConstraints方法即可
- (void)changePosition{
[redview mas_remakeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(self.view).offset(20);
make.top.equalTo(self.view).offset(100);
make.right.equalTo(self.view).offset(-20);
make.height.equalTo(@50);
}];
[blueview mas_remakeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(self->redview.mas_centerX);
make.top.equalTo(self->redview.mas_bottom).offset(20);
make.right.equalTo(self->redview.mas_right);
make.height.equalTo(self->redview.mas_height);
}];
}
结果如图2,changebtn的位置,我们不用管,大体看一下效果即可