Masonry使用总结
一、Masonry简介
Masonry是一个轻量级的布局框架,适用于
iOS
以及OS X
。它用简洁的语法对官方的AutoLayout
进行了封装。 Masonry有它自己的一套框架用来描述NSLayoutConstraints
布局的DSL
,提高了约束代码的简洁性与可读性。
Masonry现处于bugfix only
状态,将不再有功能性的更新。会有更多的开发者加入Swift
阵营,推荐使用Swift写的Snapkit
框架来布局。
二、导入Masonry框架
- 使用
Cocoapods
来导入框架,在使用到该框架的文件中添加主头文件:#import
。
- 可以参考这篇文章来配置使用
Cocoapods
-- > Cocoapods的安装和使用
- 使用直接拖拽的方式拉入框架文件夹,在使用到该框架的文件中添加主头文件:
#import "Masonry.h"
。
三、Masonry的特性
MASViewAttribute
|MASViewAttribute |NSLayoutAttribute
|:----: |:----:
|MASViewAttribute |NSLayoutAttribute
|view.mas_left |NSLayoutAttributeLeft
|view.mas_right |NSLayoutAttributeRight
|view.mas_top |NSLayoutAttributeTop
|view.mas_bottom |NSLayoutAttributeBottom
|view.mas_leading |NSLayoutAttributeLeading
|view.mas_trailing |NSLayoutAttributeTrailing
|view.mas_width |NSLayoutAttributeWidth
|view.mas_height |NSLayoutAttributeHeight
|view.mas_centerX |NSLayoutAttributeCenterX
|view.mas_centerY |NSLayoutAttributeCenterY
|view.mas_baseline |NSLayoutAttributeBaseline简化前缀的宏定义
- 为了增加代码的可读性这里有两个简化代码的宏:
#define MAS_SHORTHAND
和#define MAS_SHORTHAND_GLOBALS
-
MAS_SHORTHAND
:只要在导入Masonry
主头文件之前定义这个宏, 那么以后在使用Masonry
框架中的属性和方法的时候, 就可以省略mas_
前缀 -
MAS_SHORTHAND_GLOBALS
:只要在导入Masonry
主头文件之前定义这个宏,那么就可以让equalTo
函数接收基本数据类型, 内部会对基本数据类型进行包装
注意:这两个宏如果想有效使用,必须要在添加Masonry
头文件之前导入进去。在没有增加宏`MAS_SHORTHAND_GLOBALS时,下面这句是会报错的。
make.top.equalTo(42);--> make.top.equalTo([NSNumber numberWithInt:42]);
四、Masonry约束添加步骤
- 自定义
UIView
。 - 将自定义的
UIView
添加到父视图上。 - 添加约束
五、Masonry
的具体使用
对一个控件添加约束条件要最终满足可以确定这个空间的大小和位置,否则会报错缺少约束,当然也要避免约束冲突。下面对
View1
的左右上下(位置)都进行约束,并没有对其大小进行约束,但是可根据上述约束自动设置View1
的大小。
1. 创建一个View,左右上下空出10个像素
UIView *view1 = [[UIView alloc]init];
view1.backgroundColor = [UIColor greenColor];
[self.view addSubview:view1];
UIEdgeInsets padding = UIEdgeInsetsMake(150, 30, 30, 30);
[view1 mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(self.view.mas_top).with.offset(padding.top);
make.left.equalTo(self.view.mas_left).with.offset(padding.left);
make.bottom.equalTo(self.view.mas_bottom).with.offset(-padding.bottom);
make.right.equalTo(self.view.mas_right).with.offset(-padding.right);
}];
// 一句代码代替上面的多行
// [view1 mas_makeConstraints:^(MASConstraintMaker *make) {
// make.edges.equalTo(self.view).with.insets(UIEdgeInsetsMake(150, 30, 30, 30));
// }];
2. 使用Priority
属性来做简单的动画
.priority
allows you to specify an exact priority
.priorityHigh
equivalent to UILayoutPriorityDefaultHigh
.priorityMedium
is half way between high and low
.priorityLow
equivalent to UILayoutPriorityDefaultLow
- 优先级约束一般放在一个控件约束的最后面,下面看示例。
// 红色View
UIView *redView = [[UIView alloc]init];
redView.backgroundColor = [UIColor redColor];
[self.view addSubview:redView];
// 蓝色View
self.blueView = [[UIView alloc]init];
self.blueView.backgroundColor = [UIColor blueColor];
[self.view addSubview:self.blueView];
// 黄色View
UIView *yellowView = [[UIView alloc]init];
yellowView.backgroundColor = [UIColor yellowColor];
[self.view addSubview:yellowView];
// ---红色View--- 添加约束
[redView mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.mas_equalTo(self.view.mas_left).with.offset(20);
make.bottom.mas_equalTo(self.view.mas_bottom).with.offset(-80);
make.height.equalTo([NSNumber numberWithInt:50]);
}];
// ---蓝色View--- 添加约束
[self.blueView mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.mas_equalTo(redView.mas_right).with.offset(40);
make.bottom.width.height.mas_equalTo(redView);
}];
// ---黄色View--- 添加约束
[yellowView mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.mas_equalTo(self.blueView.mas_right).with.offset(40);
make.right.mas_equalTo(self.view.mas_right).with.offset(-20);
make.bottom.width.height.mas_equalTo(redView);
// 优先级设置为250,最高1000(默认)
make.left.mas_equalTo(redView.mas_right).with.offset(20).priority(250);
}];
// 点击屏幕移除蓝色View
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self.blueView removeFromSuperview];
[UIView animateWithDuration:1.0 animations:^{
[self.view layoutIfNeeded];
}];
}
解:这里的三个View的宽度是根据约束自动推断设置的,对黄色的View设置了一个与红色View有关的
priority(250)
的优先级,它同时有对蓝色View有个最高的优先级约束(make.left.mas_equalTo(self.blueView.mas_right).with.offset(40);
)。当点击屏幕是,我将蓝色View移除,此时第二优先级就是生效。
3. Masonry官方Demo之Basic
- (void)testBasic
{
int padding = 15;
UIView *greenView = [[UIView alloc]init];
[self.view addSubview:greenView];
greenView.backgroundColor = [UIColor greenColor];
UIView *redView = [[UIView alloc]init];
[self.view addSubview:redView];
redView.backgroundColor = [UIColor redColor];
UIView *blueView = [[UIView alloc]init];
[self.view addSubview:blueView];
blueView.backgroundColor = [UIColor blueColor];
// 对 绿色View 进行约束
[greenView mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.mas_equalTo(self.view.mas_left).with.offset(padding); // X
make.top.mas_equalTo(self.view.mas_top).with.offset(padding); // Y
make.bottom.mas_equalTo(blueView.mas_top).with.offset(-padding);// Y --> 推断出 Height
make.width.mas_equalTo(redView); // Width == 红色View(它推断出Width)
}];
// 对 红色View 进行约束
[redView mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.mas_equalTo(greenView.mas_right).with.offset(padding); // X
make.right.mas_equalTo(self.view.mas_right).with.offset(-padding);// X --> 推断出 Width
make.bottom.and.height.mas_equalTo(greenView); // Y & Height == 绿色View(它推断出 Height&Y)
}];
// 对 蓝色View 进行约束
[blueView mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.mas_equalTo(self.view.mas_left).with.offset(padding); // X
make.right.mas_equalTo(self.view.mas_right).with.offset(-padding); // X --> 推断出 Width
make.bottom.mas_equalTo(self.view.mas_bottom).with.offset(-padding); // Y
make.height.mas_equalTo(greenView); // 注意1:Height == 绿色View(它推断出Height)
}];
}
总结:对
绿色View
约束了距离左边
的距离(即确定了X值
),约束了距离顶部
和底部蓝色View
的距离(这里有个坑需要注意,很多人会认为约束了这两个就能推断出Height
,其实是错误的。除非蓝色View
添加一个约束让它们俩高度相同
,否则即便知道了它们俩间距
和分别对顶部
和底部
的距离,也不知道红色View
和蓝色View
高度如何。)
口诀:谁推断出大小位置(一或多),与其有约束关系的View的大小位置(一或多)向它看齐。
4. Masonry的更新约束 mas_updateConstraints
Alternatively if you are only updating the constant value of the constraint you can use the convience method
mas_updateConstraints
instead ofmas_makeConstraints
创建一个按钮,约束好它的位置(居中,宽高等于100且小于屏幕宽高值)。每次点击一次这个按钮,其宽高将增大一定的倍数,最终其宽高等于屏幕宽高时将不再变化。
@interface ViewController ()
@property (nonatomic, strong) UIButton *growingButton;
@property (nonatomic, assign) CGFloat scacle;
@end
- (void)createGrowingButton {
self.growingButton = [UIButton buttonWithType:UIButtonTypeSystem];
[self.growingButton setTitle:@"点我放大" forState:UIControlStateNormal];
self.growingButton.layer.borderColor = UIColor.greenColor.CGColor;
self.growingButton.layer.borderWidth = 3;
[self.growingButton addTarget:self action:@selector(onGrowButtonTaped:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:self.growingButton];
self.scacle = 1.0;
[self.growingButton mas_makeConstraints:^(MASConstraintMaker *make) {
make.center.mas_equalTo(self.view);
// 初始宽、高为100,优先级最低
make.width.height.mas_equalTo(100 * self.scacle);
// 最大放大到整个view
make.width.height.lessThanOrEqualTo(self.view);
}];
}
- (void)onGrowButtonTaped:(UIButton *)sender {
self.scacle += 1.0;
// 告诉self.view约束需要更新
[self.view setNeedsUpdateConstraints];
// 调用此方法告诉self.view检测是否需要更新约束,若需要则更新,下面添加动画效果才起作用
[self.view updateConstraintsIfNeeded];
[UIView animateWithDuration:0.3 animations:^{
[self.view layoutIfNeeded];
}];
}
#pragma mark - updateViewConstraints
// 重写该方法来更新约束
- (void)updateViewConstraints {
[self.growingButton mas_updateConstraints:^(MASConstraintMaker *make) {
// 这里写需要更新的约束,不用更新的约束将继续存在
// 不会被取代,如:其宽高小于屏幕宽高不需要重新再约束
make.width.height.mas_equalTo(100 * self.scacle);
}];
[super updateViewConstraints];
}
5. Masonry的重写约束 mas_remakeConstraints
Creates a MASConstraintMaker with the callee view. Any constraints defined are added to the view or the appropriate superview once the block has finished executing. All constraints previously installed for the view will be removed.
创建一个按钮,约束好其位置(与屏幕上左右的距离为0,与屏幕底部距离为350),点击按钮后全屏展现(即与屏幕底部距离为0)。
@property (nonatomic, strong) UIButton *growingButton;
@property (nonatomic, assign) BOOL isExpanded;
- (void)createExpandButton {
self.isExpanded = NO;
self.growingButton = [UIButton buttonWithType:UIButtonTypeSystem];
[self.growingButton setTitle:@"点我展开" forState:UIControlStateNormal];
self.growingButton.layer.borderColor = UIColor.greenColor.CGColor;
self.growingButton.layer.borderWidth = 3;
self.growingButton.backgroundColor = [UIColor redColor];
[self.growingButton addTarget:self action:@selector(onGrowButtonTaped:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:self.growingButton];
[self.growingButton mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.mas_equalTo(0);
make.left.right.mas_equalTo(0);
make.bottom.mas_equalTo(-350);
}];
}
#pragma mark - updateViewConstraints
- (void)updateViewConstraints {
// 这里使用update也能实现效果
// remake会将之前的全部移除,然后重新添加
__weak __typeof(self) weakSelf = self;
[self.growingButton mas_remakeConstraints:^(MASConstraintMaker *make) {
// 这里重写全部约束,之前的约束都将失效
make.top.mas_equalTo(0);
make.left.right.mas_equalTo(0);
if (weakSelf.isExpanded) {
make.bottom.mas_equalTo(0);
} else {
make.bottom.mas_equalTo(-350);
}
}];
[super updateViewConstraints];
}
- (void)onGrowButtonTaped:(UIButton *)sender {
self.isExpanded = !self.isExpanded;
if (!self.isExpanded) {
[self.growingButton setTitle:@"点我展开" forState:UIControlStateNormal];
} else {
[self.growingButton setTitle:@"点我收起" forState:UIControlStateNormal];
}
// 告诉self.view约束需要更新
[self.view setNeedsUpdateConstraints];
// 调用此方法告诉self.view检测是否需要更新约束,若需要则更新,下面添加动画效果才起作用
[self.view updateConstraintsIfNeeded];
[UIView animateWithDuration:0.3 animations:^{
[self.view layoutIfNeeded];
}];
}
-
mas_remakeConstraints
和mas_updateConstraints
的区别在于前者重新对视图进行了约束(抛弃了之前的约束),后者是更新约束条件(保留未更新的约束,如:这次更新了对height
的约束,其他对X&Y以及宽的约束不变)。
6. Masonry的比例使用 multipliedBy
使用multipliedBy必须是对同一个控件本身,如果修改成相对于其它控件会出导致Crash。
UIView *topView = [[UIView alloc]init];
[topView setBackgroundColor:[UIColor redColor]];
[self.view addSubview:topView];
UIView *topInnerView = [[UIView alloc]init];
[topInnerView setBackgroundColor:[UIColor greenColor]];
[topView addSubview:topInnerView];
UIView *bottomView = [[UIView alloc]init];
[bottomView setBackgroundColor:[UIColor orangeColor]];
[self.view addSubview:bottomView];
UIView *bottomInnerView = [[UIView alloc]init];
[bottomInnerView setBackgroundColor:[UIColor blueColor]];
[bottomView addSubview:bottomInnerView];
[topView mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.left.right.mas_equalTo(0);
make.height.mas_equalTo(bottomView);
}];
[topInnerView mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.right.mas_equalTo(0);
make.width.mas_equalTo(topInnerView.mas_height).multipliedBy(3);
make.center.mas_equalTo(topView);
}];
[bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.bottom.right.mas_equalTo(0);
make.height.mas_equalTo(topView);
make.top.mas_equalTo(topView.mas_bottom);
}];
[bottomInnerView mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.bottom.mas_equalTo(bottomView);
make.height.mas_equalTo(bottomInnerView.mas_width).multipliedBy(3);
make.center.mas_equalTo(bottomView);
}];