简介:
相对于官方的NSLayoutConstraints的的过于繁琐和麻烦,Masonry是一个轻量级的布局框架 拥有自己的描述语法 采用更优雅的链式语法封装自动布局 简洁明了 并具有高可读性 而且同时支持 iOS 和 Max OS X。可以到Masonry-Github下载官方源码Demo
安装:
1.直接进入github进行源码下载 引入头文件#import "Masonry.h"
2.使用CocoaPod进行下载pod 'Masonry'
简单使用
- Masonry的属性:
Masonry NSAutoLayout 说明
left NSLayoutAttributeLeft 左侧
top NSLayoutAttributeTop 上侧
right NSLayoutAttributeRight 右侧
bottom NSLayoutAttributeBottom 下侧
leading NSLayoutAttributeLeading 首部
trailing NSLayoutAttributeTrailing 尾部
width NSLayoutAttributeWidth 宽
height NSLayoutAttributeHeight 高
centerX NSLayoutAttributeCenterX 横向中点
centerY NSLayoutAttributeCenterY 纵向中点
baseline NSLayoutAttributeBaseline 文本基线
- Masonry的属性:
- 最常用的三种加约束的方式:
//mas_makeConstraints 只负责新增约束 Autolayout不能同时存在两条针对于同一对象的约束 否则会报错
- (NSArray *)mas_makeConstraints:(void(^)(MASConstraintMaker *make))block;//mas_updateConstraints 针对上面的情况 会更新在block中出现的约束 不会导致出现两个相同约束的情况
- (NSArray *)mas_updateConstraints:(void(^)(MASConstraintMaker *make))block;//mas_remakeConstraints 则会清除之前的所有约束 仅保留最新的约束
- (NSArray *)mas_remakeConstraints:(void(^)(MASConstraintMaker *make))block;
比如,要给一个视图加约束为距父视图上下左右边距都为10
UIView *subView = [[UIView alloc]init];subView.backgroundColor = [UIColor blackColor];[self.view addSubview:subView];CGFloat margin = 10;[subView mas_makeConstraints:^(MASConstraintMaker *make) {make.left.equalTo(self.view).offset(margin);make.right.equalTo(self.view).offset(-margin);make.top.equalTo(self.view).offset(margin);make.bottom.equalTo(self.view).offset(-margin);}];
也可以这样写:
UIView *subView = [[UIView alloc]init];subView.backgroundColor = [UIColor blackColor];[self.view addSubview:subView];CGFloat margin = 10;[subView mas_makeConstraints:^(MASConstraintMaker *make) {make.top.left.bottom.and.right.equalTo(self.view).with.insets(UIEdgeInsetsMake(margin, margin, -margin, -margin));}];
或者这样写:
UIView *subView = [[UIView alloc]init];subView.backgroundColor = [UIColor blackColor];[self.view addSubview:subView];CGFloat margin = 10;[subView mas_makeConstraints:^(MASConstraintMaker *make) {make.edges.equalTo(self.view).with.insets(UIEdgeInsetsMake(margin, margin, -margin, -margin));}];
注意:
- 在xib或者storyboard中使用masonry框架相关方法的时候要将use Auto layout选项去掉,否则会不起作用。
- 给一个View加约束前提是该视图有父视图(superView),否则会报错
- 给一个view1添加约束时与相对的view2之间必须有父子视图或者有一个共同的父视图的关系