上一篇介绍了NSLayoutConstraint动态布局,代码量有点多,用起来比较烦,今天呢给大家带来一个大神封装好的Masonry的使用心得。
使用很简单,把Masonry拖入项目项目中引入#import "Masonry.h"就好了。这个第三方框架大大简化了布局代码量。其思想也是目标对象和参照对象的比较来的。话不多说,举个例子就好了。
UILabel *label1 = [[UILabel alloc] init];
UILabel *label2 = [[UILabel alloc] init];
UILabel *label3 = [[UILabel alloc] init];
UILabel *label4 = [[UILabel alloc] init];
UILabel *label5 = [[UILabel alloc] init];
[self.view addSubview:label1];
[self.view addSubview:label2];
[self.view addSubview:label3];
[self.view addSubview:label4];
[self.view addSubview:label5];
label1.backgroundColor = [UIColor greenColor];
label2.backgroundColor = [UIColor yellowColor];
label3.backgroundColor = [UIColor redColor];
label4.backgroundColor = [UIColor orangeColor];
label5.backgroundColor = [UIColor purpleColor];
label1.text = @"第一个";
label2.text = @"第二个";
label3.text = @"第三个";
label4.text = @"第四个";
label5.text = @"第五个";
[label1 mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.mas_equalTo(@30);
make.leading.equalTo(@8);
make.width.mas_equalTo((self.view.width-36)/3);
make.height.equalTo(label1.mas_width);
}];
[label2 mas_makeConstraints:^(MASConstraintMaker *make) {
make.leading.equalTo(label1.mas_trailing).offset(10);
make.width.mas_equalTo((self.view.width-36)/3);
make.height.equalTo(label2.mas_width);
make.top.mas_equalTo(label1.mas_bottom).offset(10);
}];
[label3 mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.mas_equalTo(@30);
make.leading.equalTo(label2.mas_trailing).offset(10);
make.width.mas_equalTo((self.view.width-36)/3);
make.height.equalTo(label3.mas_width);
}];
[label4 mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.mas_equalTo(label2.mas_bottom).offset(10);
make.leading.equalTo(@8);
make.width.mas_equalTo((self.view.width-36)/3);
make.height.equalTo(label3.mas_width);
}];
[label5 mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.mas_equalTo(label2.mas_bottom).offset(10);
make.leading.equalTo(label2.mas_trailing).offset(10);
make.width.mas_equalTo((self.view.width-36)/3);
make.height.equalTo(label3.mas_width);
}];
下面是效果图: