前提
经过一点时间的使用,发现在网上很少有Masonry的教程,也仅仅有那么一两篇而已,在此我编写一下我最近一段时间使用的方法,供大家学习。
Masonry是AutoLayout的一个第三方类库,用链式语法封装了冗长的AutoLayout代码,因此学习成本相对于官方提供的AutoLayout,以及VFL语言而言,低上很多很多…
准备
在GitHub上 https://github.com/SnapKit/Masonry 下载配置第三方库,基本使用方法在Readme中也有说明,我就不赘述了,CocoaPods在我blog有相关的设置介绍 CocoaPods的安装使用
pod 'Masonry'
为了方便更新库来解决旧有bug,所以不写版本号 ‘~>x.x.x’
在pch文件中加入
#import "Masonry.h"
便可全局使用
基本用法
可以理解和Android五大布局中的相对布局一样,基本原理就是本控件相对于某个控件的位置,因此相对比较需要有一个参考控件
基本的计算公式为
控件左边 = 参考控件的右边 + 偏移值(5) (控件在参考控件的右边,距离其5px)
make.left.equalTo(view.superview.mas_right).offset(10);//不填则默认对应left,其他同理
支持的属性
@property (nonatomic, strong, readonly) MASConstraint *left;
@property (nonatomic, strong, readonly) MASConstraint *top;
@property (nonatomic, strong, readonly) MASConstraint *right;
@property (nonatomic, strong, readonly) MASConstraint *bottom;
@property (nonatomic, strong, readonly) MASConstraint *leading;
@property (nonatomic, strong, readonly) MASConstraint *trailing;
@property (nonatomic, strong, readonly) MASConstraint *width;
@property (nonatomic, strong, readonly) MASConstraint *height;
@property (nonatomic, strong, readonly) MASConstraint *centerX;
@property (nonatomic, strong, readonly) MASConstraint *centerY;
@property (nonatomic, strong, readonly) MASConstraint *baseline;
方法
Masonry有三种设置约束的方法
mas_makeConstraints //第一次生成约束使用
mas_updateConstraints //更新其中的约束
mas_remakeConstraints //重新生成约束,会将之前的所有约束先去掉
使用注意:在循环cell,如果有代码重复调用的地方,一定要使用mas_remakeConstraints,以此防止循环的时候生成相同的约束,影响性能,甚至,能使用make的地方基本都可以用remake进行代替,防止生成无谓的约束
简单用法
初始化一个带边距的view
UIView *view = [[UIView alloc] init];
view.backgroundColor = [UIColor redColor];
[self.view addSubview:view];//一定要先加入父控件,否则