美文网首页
Masonry使用详解

Masonry使用详解

作者: XZ_Henry | 来源:发表于2017-11-29 18:57 被阅读0次

Masonry -- 使用纯代码进行iOS应用的autolayout自适应布局,对很多零散的进行整理

 简介

简化iOS应用使用纯代码机型自适应布局的工作,使用一种简洁高效的语法替代NSLayoutConstraints.

项目主页: Masonry

最新示例: 点击下载

项目简议: 如果再看到关于纯代码,xib或storyboard,使用哪种方式进行UI布局更合适的讨论,请推荐他们先试用下 Masonry. Masonry,像xib一样快速,同时拥有作为纯代码方式的灵活性 -- github关注度 7800 + 是有原因的!

快速入门

安装

使用 CocoaPods 安装

```

pod 'Masonry'

```

推荐在你的在 prefix.pch 中引入头文件:

```

// 定义这个常量,就可以在使用Masonry不必总带着前缀 `mas_`:

#define MAS_SHORTHAND

// 定义这个常量,以支持在 Masonry 语法中自动将基本类型转换为 object 类型:

#define MAS_SHORTHAND_GLOBALS

#import "Masonry.h"

```

使用

初始Masonry

这是使用MASConstraintMaker创建的约束:

```

/* 注意:view1应首先添加为某个视图的子视图,superview是一个局部变量,指view1的父视图. */

UIEdgeInsets padding = UIEdgeInsetsMake(10, 10, 10, 10);

[view1 mas_makeConstraints:^(MASConstraintMaker *make) {

make.top.equalTo(superview.mas_top).offset(padding.top);

make.left.equalTo(superview.mas_left).offset(padding.left);

make.bottom.equalTo(superview.mas_bottom).offset(-padding.bottom);

make.right.equalTo(superview.mas_right).offset(-padding.right);

}];

```

甚至可以更短:

```

[view1 mas_makeConstraints:^(MASConstraintMaker *make) {

make.edges.equalTo(superview).insets(padding);

}];

```

## 不止可以表达相等关系

> `.equalTo` 等价于 NSLayoutRelationEqual

> `.lessThanOrEqualTo` 等价于 NSLayoutRelationLessThanOrEqual

> `.greaterThanOrEqualTo` 等价于 NSLayoutRelationGreaterThanOrEqual

这三个表达相等关系的语句,可以接受一个参数;此参数可以为以下任意一个:

1、MASViewAttribute

```

make.centerX.lessThanOrEqualTo(view2.mas_left);

```

| 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 |

2、UIView/NSView

如果你需要 view.left 大于或等于label.left:

```

// 下面两个约束是完全等效的.

make.left.greaterThanOrEqualTo(label);

make.left.greaterThanOrEqualTo(label.mas_left);

```

3、NSNumber

自适应布局允许将宽度或高度设置为固定值.如果你想要给视图一个最小或最大值,你可以这样:

```

//width >= 200 && width <= 400

make.width.greaterThanOrEqualTo(@200);

make.width.lessThanOrEqualTo(@400)

```

但是自适应布局不支持将 left,right, centerY等设为固定值.如果你给这些属性传递一个常量, Masonry会自动将它们转换为相对于其父视图的相对值:

```

//creates view.left = view.superview.left + 10

make.left.lessThanOrEqualTo(@10)

```

除了使用 NSNumber 外,你可以使用基本数据类型或者结构体来创建约束:

```

make.top.mas_equalTo(42);

make.height.mas_equalTo(20);

make.size.mas_equalTo(CGSizeMake(50, 100));

make.edges.mas_equalTo(UIEdgeInsetsMake(10, 0, 10, 0));

make.left.mas_equalTo(view).mas_offset(UIEdgeInsetsMake(10, 0, 10, 0));

```

4、NSArry

一个数组,里面可以混合是前述三种类型的任意几种:

```

// 表达三个视图等高的约束.

make.height.equalTo(@[view1.mas_height, view2.mas_height]);

make.height.equalTo(@[view1, view2]);

make.left.equalTo(@[view1, @100, view3.right]);

```

#### 两个特殊的等比方法

* 第一种

![](https://img.haomeiwen.com/i2162015/da44bf4b329efc83.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

```

//在红色View里面放三个正方形View, 等间距为10

NSInteger padding = 10;

UIView *yellowView1 = [[UIView alloc] init];

yellowView1.backgroundColor = [UIColor yellowColor];

[redView addSubview:yellowView1];

UIView *yellowView2 = [[UIView alloc] init];

yellowView2.backgroundColor = [UIColor yellowColor];

[redView addSubview:yellowView2];

UIView *yellowView3 = [[UIView alloc] init];

yellowView3.backgroundColor = [UIColor yellowColor];

[redView addSubview:yellowView3];

[@[yellowView1, yellowView2, yellowView3] mas_distributeViewsAlongAxis:MASAxisTypeHorizontal withFixedSpacing:padding leadSpacing:padding tailSpacing:padding];

[@[yellowView1, yellowView2, yellowView3] mas_makeConstraints:^(MASConstraintMaker *make) {

make.top.equalTo(redView).offset(10);

make.height.mas_equalTo(yellowView3.mas_width);

}];

```

```

/**

*  确定间距等间距布局

*

*  @param axisType    布局方向

*  @param fixedSpacing 两个item之间的间距(最左面的item和左边, 最右边item和右边都不是这个)

*  @param leadSpacing  第一个item到父视图边距

*  @param tailSpacing  最后一个item到父视图边距

*/

- (void)mas_distributeViewsAlongAxis:(MASAxisType)axisType withFixedSpacing:(CGFloat)fixedSpacing leadSpacing:(CGFloat)leadSpacing tailSpacing:(CGFloat)tailSpacing;

```

所以也就知道了, 将`fixedSpacing`, `leadSpacing`, `tailSpacing`都赋值同一个间距, 数组内的的View就会自动计算出宽度, 完成水平方向的布局.

要注意的是, 这个方法仅仅完成了水平方向的布局, 如果想确定这几个View的位置, 还需要指定竖直方向位置和高度, 这里可以用数组直接调用 `mas_makeConstraints:^(MASConstraintMaker *make){}`完成布局.

* 第二种

![](https://img.haomeiwen.com/i2162015/f1e9484bda5f5612.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

```

/**

*  distribute with fixed item size

*

*  @param axisType  布局方向

*  @param fixedItemLength 每个item的布局方向的长度

*  @param leadSpacing  第一个item到父视图边距

*  @param tailSpacing  最后一个item到父视图边距

*/

- (void)mas_distributeViewsAlongAxis:(MASAxisType)axisType withFixedItemLength:(CGFloat)fixedItemLength leadSpacing:(CGFloat)leadSpacing tailSpacing:(CGFloat)tailSpacing;

```

区别就是这里除了布局方向, 第一个和最后一个View的边距, 这里需要指定的是每个item的长度, 自动计算间隙, 所以这个要实现等间距, 其实是要通过item的数量, 以及父视图的宽度先计算出间距, 然后赋值给, leadSpacing和tailSpacing, 比如`CGFloat padding2 = (300 - 3 * 30) / 4;` 这里的300就是父视图的宽度, 30是指定的每个item的宽度, 这样计算好就可以保证, leadSpacing, tailSpacing, 和item之间的间距相同, 实现布局.

同样这个方法完成了水平方向的布局, 还需要完成竖直方向的布局.

* 第三种

![](https://img.haomeiwen.com/i2162015/4cc19492281e48fe.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

```

//在红色View里面放三个大小不一样的绿色正方形, 间隙等大, masonry并没提供相关方法

NSMutableArray *greenViews = [NSMutableArray array];

for (NSInteger i = 0; i < 3; i++) {

UIView *greenView = [[UIView alloc] init];

greenView.backgroundColor = [UIColor greenColor];

[redView addSubview:greenView];

[greenViews addObject:greenView];

[greenView mas_makeConstraints:^(MASConstraintMaker *make) {

make.bottom.equalTo(redView).offset(-10);

make.width.mas_equalTo(i*20 + 20);

make.height.mas_equalTo(greenView.mas_width);

}];

}

[redView distributeSpacingHorizontallyWith:greenViews];

```

首先在for循环内 , 完成了底部位置, 宽, 高的布局, 还缺少水平方向的位置, 即还要确定每个view的X, 这里用到了一个UIView的分类

`- (void) distributeSpacingHorizontallyWith:(NSArray*)views;`

这个分类直接用的里脊串的一篇文章中的代码, 就不贴出代码了, 简单说一下原理, 如图所示:

![](https://img.haomeiwen.com/i2162015/7611cd1ea333175e.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

实现原理就是在View中创建greenViews.count + 1个占位的View(蓝色), 之后通过布局, 使占位View与要布局的View依次排开, 左右间距为0, 同时要约束所有的占位View宽度相等, 这样看来, 这些占位View的宽度, 就是greenViews的间距, 也就可以实现等间距布局了.

## 约束的优先级

> `.priority` 允许你指定一个精确的优先级,数值越大优先级越高.最高1000.

> `.priorityHigh` 等价于 UILayoutPriorityDefaultHigh.优先级值为 750.

> `.priorityMedium` 介于高优先级和低优先级之间,优先级值在 250~750之间.

> `.priorityLow` 等价于 UILayoutPriorityDefaultLow, 优先级值为 250.

优先级可以在约束的尾部添加:

```

make.left.greaterThanOrEqualTo(label.mas_left).with.priorityLow();

make.top.equalTo(label.mas_top).with.priority(600);

```

## 等比例自适应

> `.multipliedBy` 允许你指定一个两个视图的某个属性等比例变化

>

> `item1.attribute1 = multiplier × item2.attribute2 + constant`,此为约束的计算公式, `.multipliedBy`本质上是用来限定 `multiplier`的

> 注意,因为编程中的坐标系从父视图左上顶点开始,所以指定基于父视图的left或者top的multiplier是没有意义的,因为父视图的left和top总为0.

> 如果你需要一个视图随着父视图的宽度和高度,位置自动变化,你应该同时指定 right,bottom,width,height与父视图对应属性的比例(基于某个尺寸下的相对位置计算出的比例),并且constant必须为0.

```

// 指定宽度为父视图的 1/4.

make.width.equalTo(superview).multipliedBy(0.25);

```

## 工具方法

Masonry提供了一些工具方法来进一步简化约束的创建.

### edges 边界

```

//使 top, left, bottom, right等于 view2

make.edges.equalTo(view2);

//使 top = superview.top + 5, left = superview.left + 10,

//      bottom = superview.bottom - 15, right = superview.right - 20

make.edges.equalTo(superview).insets(UIEdgeInsetsMake(5, 10, 15, 20))

```

### size 尺寸

```

// 使宽度和高度大于或等于 titleLabel

make.size.greaterThanOrEqualTo(titleLabel)

//使 width = superview.width + 100, height = superview.height - 50

make.size.equalTo(superview).sizeOffset(CGSizeMake(100, -50))

```

### center 中心

```

//使 centerX和 centerY = button1

make.center.equalTo(button1)

//使 centerX = superview.centerX - 5, centerY = superview.centerY + 10

make.center.equalTo(superview).centerOffset(CGPointMake(-5, 10))

```

你可以使用链式语法来增强代码可读性:

```

// 除top外,其他约束都与父视图相等.

make.left.right.bottom.equalTo(superview);

make.top.equalTo(otherView);

```

## 更新约束

有时,你需要修改已经存在的约束来实现动画效果或者移除/替换已有约束.在 Masonry 中,有几种不同的更新视图约束的途径:

#### 1、References 引用

你可以把 Masonry 语法返回的约束或约束数组,存储到一个局部变量或者类的属性中,以供后续操作某个约束.

```

// 声明属性

@property (nonatomic, strong) MASConstraint *topConstraint;

...

// when making constraints

[view1 mas_makeConstraints:^(MASConstraintMaker *make) {

self.topConstraint = make.top.equalTo(superview.mas_top).with.offset(padding.top);

make.left.equalTo(superview.mas_left).with.offset(padding.left);

}];

...

// 然后你就可以操作这个属性.

[self.topConstraint uninstall];

```

#### 2、mas_updateConstraints

如果你只是想添加新的约束,你可以使用便利方法mas_updateConstraints,不需要使用 mas_makeConstraints. mas_updateConstraints,不会移除已经存在的约束(即使新旧约束间相互冲突).

```

// 重写视图的updateConstraints方法: 这是Apple推荐的添加/更新约束的位置.

// 这个方法可以被多次调用以响应setNeedsUpdateConstraints方法.

// setNeedsUpdateConstraints 可以被UIKit内部调用或者由开发者在自己的代码中调用以更新视图约束.

- (void)updateConstraints {

[self.growingButton mas_updateConstraints:^(MASConstraintMaker *make) {

make.center.equalTo(self);

make.width.equalTo(@(self.buttonSize.width)).priorityLow();

make.height.equalTo(@(self.buttonSize.height)).priorityLow();

make.width.lessThanOrEqualTo(self);

make.height.lessThanOrEqualTo(self);

}];

//根据apple机制,最后应调用父类的updateConstraints方法.

[super updateConstraints];

}

```

#### 3. mas_remakeConstraints

`mas_remakeConstraints`与`mas_updateConstraints`相似,不同之处在于: `mas_remakeConstraints` 会先移除视图上已有的约束,再去创建新的约束.

```

- (void)changeButtonPosition {

[self.button mas_remakeConstraints:^(MASConstraintMaker *make) {

make.size.equalTo(self.buttonSize);

if (topLeft) {

make.top.and.left.offset(10);

} else {

make.bottom.and.right.offset(-10);

}

}];

}

```

相关文章

网友评论

      本文标题:Masonry使用详解

      本文链接:https://www.haomeiwen.com/subject/esspbxtx.html