- 使用 Masonry 时,有时候我们需要同时在一个父控件上布局一系列等宽高的控件,如下图:
实现思路:
Masonry 里有两个这样的属性
centerX NSLayoutAttributeCenterX 横向中点
centerY NSLayoutAttributeCenterY 纵向中点
我们通过上边的这两个属性帮助我们实现
左侧的 view 约束设置:(距离黑色 view 左侧的距离、centerY(纵向中心,相当于确定了 Y 值)、view 的高度与 self.view 的高度比,还有一个视图自身的宽高相等);
中间的 view 约束设置: ( centerX 、 centerY 、自身宽高相等, 自身和self.view 的高度比,高度也可以和黑色的 View 对比,这里只是一个动态的高度比);
右侧的跟左侧的很像,唯一区别,需要将右侧进行约束;
切换横竖屏我们看一下效果
代码如下:
- 由于使用了 Block 需要注意循环引用问题
__weak typeof(self) weakSelf = self
;
__weak typeof(self) weakSelf = self;
self.viewForBottom = [[UIImageView alloc]init];
[self.view addSubview:self.viewForBottom];
self.viewForBottom.backgroundColor = [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:1.0];
[self.viewForBottom mas_makeConstraints:^(MASConstraintMaker *make) {
make.bottom.equalTo(weakSelf.view).offset(0);
make.left.equalTo(weakSelf.view).offset(0);
make.right.equalTo(weakSelf.view).offset(0);
make.height.equalTo(weakSelf.view.mas_height).multipliedBy(1/13.0f);
}];
self.cropButton = [[UIButton alloc]init];
self.previewButton = [[UIButton alloc]init];
self.saveButton = [[UIButton alloc]init];
[self.viewForBottom addSubview:self.saveButton];
[self.viewForBottom addSubview:self.cropButton];
[self.viewForBottom addSubview:self.previewButton];
self.cropButton.backgroundColor = [UIColor colorWithRed:0.8 green:1.0 blue:0.4 alpha:1.0];
self.saveButton.backgroundColor = [UIColor colorWithRed:1.0 green:0.8 blue:0.4 alpha:1.0];
self.previewButton.backgroundColor = [UIColor yellowColor];
[self.cropButton mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(weakSelf.viewForBottom).offset(40);
//中心 Y
make.centerY.equalTo(weakSelf.viewForBottom);
make.height.equalTo(weakSelf.cropButton.mas_width);
make.height.equalTo(weakSelf.view.mas_height).multipliedBy(1/25.0f);
}];
[self.previewButton mas_makeConstraints:^(MASConstraintMaker *make) {
//中心 Y
make.centerX.equalTo(weakSelf.viewForBottom);
make.centerY.equalTo(weakSelf.viewForBottom);
make.height.equalTo(weakSelf.previewButton.mas_width);
make.height.equalTo(weakSelf.view.mas_height).multipliedBy(1/25.0f);
}];
[self.saveButton mas_makeConstraints:^(MASConstraintMaker *make) {
make.right.equalTo(weakSelf.viewForBottom).offset(-40);
make.centerY.equalTo(weakSelf.viewForBottom);
make.height.equalTo(weakSelf.saveButton.mas_width);
make.height.equalTo(weakSelf.view.mas_height).multipliedBy(1/25.0f);
}];