#import "MAExampleBasicView.h"
#import "Masonry.h"
@implementation MAExampleBasicView
- (instancetype)init
{
self = [super init];
if (self) {
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;
// redView.hidden = YES;
[self addSubview:redView];
UIView *blueView = [UIView new];
blueView.backgroundColor = [UIColor blueColor];
blueView.layer.borderColor = [UIColor blackColor].CGColor;
blueView.layer.borderWidth = 2;
[self addSubview:blueView];
int padding = 10;
// 绿色视图的布局约束
[greenView mas_makeConstraints:^(MASConstraintMaker *make) {
// 上左下右
make.top.greaterThanOrEqualTo(self.mas_top).offset(padding);
make.left.mas_equalTo(self.mas_left).offset(padding);
make.bottom.mas_equalTo(blueView.mas_top).offset(-padding);
make.right.mas_equalTo(redView.mas_left).offset(-padding);
make.width.equalTo(redView.mas_width);
make.height.equalTo(redView.mas_height);
make.height.equalTo(blueView.mas_height);
}];
// 红色视图布局
[redView mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(self.mas_top).with.offset(padding);
make.left.equalTo(greenView.mas_right).offset(-padding);
make.bottom.equalTo(blueView.mas_top).offset(-padding);
make.right.equalTo(self.mas_right).offset(-padding);
make.width.equalTo(greenView.mas_width);
make.height.equalTo(@[greenView,blueView]);
// 这里需要注意可以填充一个视图数组
}];
// 蓝色视图
[blueView mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(greenView.mas_bottom).offset(padding);
make.left.equalTo(self.mas_left).offset(padding);
make.bottom.equalTo(self.mas_bottom).offset(-padding);
make.right.equalTo(self.mas_right).offset(-padding);
make.height.equalTo(@[greenView.mas_height,redView.mas_height]);
}];
}
return self;
}
进行动态布局UI 可以使用xib拉约束设置 也可以使用三方库Masonry来进行设置
这里引入了三方库Masonry(使用CocoaPods管理 之前博客有介绍怎样配置 这里不再描述)
Masonry 用起来也是很方便的 只需要掌握 我们想要布局的控件基本位置 分清楚 top、left、bottom、right
方便使用 并且代码比较简洁 层次结构比较清晰。 这里写了一个简单的demo 供大家参考学习。