iOS开发 Masonry简介

简介

Masonry 是一个非常好用的iOS开发布局框架,在使用代码布局视图时,相比原生的NSLayoutConstraint,在使用容易度和代码的可阅读程度,都优秀非常多。Masonry使用了链式语法,例如:make.left.equalTo(view.mas_bottom).offset(0);不管是使用还是阅读,都是非常易懂的。
Maosnry的GitHub连接 附上GitHub的连接,在GitHub上,开发者已经对Masonry做了非常详尽的介绍,强烈推荐阅读。
Masonry本质还是基于NSLayoutConstraint进行封装的,而且连报错的信息都优化了。

(
    "<NSLayoutConstraint:0x7189ac0 V:[UILabel:0x7186980(>=5000)]>",
    "<NSAutoresizingMaskLayoutConstraint:0x839ea20 h=--& v=--& V:[MASExampleDebuggingView:0x7186560(416)]>",
    "<NSLayoutConstraint:0x7189c70 UILabel:0x7186980.bottom == MASExampleDebuggingView:0x7186560.bottom - 10>",
    "<NSLayoutConstraint:0x7189560 V:|-(1)-[UILabel:0x7186980]   (Names: '|':MASExampleDebuggingView:0x7186560 )>"
)

Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x7189ac0 V:[UILabel:0x7186980(>=5000)]>

上面的报错信息是未封装前的,类似h=--& v=--& V:这样的语法提示信息,一般也是难以理解的。Masonry将其优化成如下:

(
    "<NSAutoresizingMaskLayoutConstraint:0x8887740 MASExampleDebuggingView:superview.height == 416>",
    "<MASLayoutConstraint:ConstantConstraint UILabel:messageLabel.height >= 5000>",
    "<MASLayoutConstraint:BottomConstraint UILabel:messageLabel.bottom == MASExampleDebuggingView:superview.bottom - 10>",
    "<MASLayoutConstraint:ConflictingConstraint[0] UILabel:messageLabel.top == MASExampleDebuggingView:superview.top + 1>"
)

Will attempt to recover by breaking constraint
<MASLayoutConstraint:ConstantConstraint UILabel:messageLabel.height >= 5000>

安装

基于CocoaPod进行安装
pod 'Masonry'
在引入Masonry文件时,建议加上#define MAS_SHORTHAND,这样可以简化代码,即去掉了mas_前缀。同时,也建议加上#define MAS_SHORTHAND。这样就可以将@10简化成10
简化前的代码:

[_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(@0);
    }];

简化后的代码:

[_tableView makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(0);
    }];

引入格式:

#define MAS_SHORTHAND_GLOBALS
#define MAS_SHORTHAND
#import "Masonry.h"

使用

实例1 简单布局

image.png

如图,简单布局两个view,如上。

UIView *view1 = [UIView new];
    view1.backgroundColor = [UIColor cyanColor];
    _v1 = view1;
    UIView *view2 = [UIView new];
    view2.backgroundColor = [UIColor greenColor];
    _v2 = view2;
    
    CGFloat screenWidth = [UIApplication sharedApplication].delegate.window.bounds.size.width;
    CGFloat viewWidth = (screenWidth - 30)/2;
    
    [self.view addSubview:view1];
    [self.view addSubview:view2];
    
    [view1 makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(10);
        make.top.equalTo(100); // 与父视图的相同方位数据设置偏移
        make.height.width.equalTo(viewWidth); // 两个方位数据可以一起设置
    }];
    
    [view2 makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(view1.mas_right).offset(10); // 这里的mas_right不能去掉前缀mas_不然会报内存泄漏
        make.top.equalTo(view1).offset(0);
        make.size.equalTo(viewWidth);
    }];

Masonry布局的语法为:make.left.equalTo(view1.mas_right).offset(10); make表示被布局的视图,equalTo()方法入参为相对应视图的方位数据。这个入参不传入显式视图时:equalTo(0)则表示与父视图的相同方位数据对比。例如:make.left.equalTo(10);表示view1的顶部是相对于其父视图的顶部向下偏移10。
其方位数据有一下可供选择设置布局:

@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;
@property (nonatomic, strong, readonly) MASConstraint *firstBaseline;
@property (nonatomic, strong, readonly) MASConstraint *lastBaseline;
@property (nonatomic, strong, readonly) MASConstraint *leftMargin;
@property (nonatomic, strong, readonly) MASConstraint *rightMargin;
@property (nonatomic, strong, readonly) MASConstraint *topMargin;
@property (nonatomic, strong, readonly) MASConstraint *bottomMargin;
@property (nonatomic, strong, readonly) MASConstraint *leadingMargin;
@property (nonatomic, strong, readonly) MASConstraint *trailingMargin;
@property (nonatomic, strong, readonly) MASConstraint *centerXWithinMargins;
@property (nonatomic, strong, readonly) MASConstraint *centerYWithinMargins;
@property (nonatomic, strong, readonly) MASConstraint *edges;
@property (nonatomic, strong, readonly) MASConstraint *size;
@property (nonatomic, strong, readonly) MASConstraint *center;

实例2 动态宽度进行布局

image.png

天蓝色的视图宽高设置了一样的数值,只是因为在水平方向上,两个视图的宽度不能超过屏幕的宽度,所以就将天蓝色的视图宽度压缩了。

-(void)showDemo2{
    
    UIView *view1 = [UIView new];
    view1.backgroundColor = [UIColor cyanColor];
    _v1 = view1;
    UIView *view2 = [UIView new];
    view2.backgroundColor = [UIColor greenColor];
    _v2 = view2;
    
    CGFloat screenWidth = [UIApplication sharedApplication].delegate.window.bounds.size.width;
    CGFloat viewWidth = (screenWidth - 30)/2;
    
    [self.view addSubview:view1];
    [self.view addSubview:view2];
    
    [view1 makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(10);
        make.top.equalTo(100);
        make.height.width.lessThanOrEqualTo(screenWidth);
    }];
    
    [view2 makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(view1.mas_right).offset(10); // 这里的mas_right不能去掉前缀mas_不然会报内存泄漏
        make.top.equalTo(view1).offset(0);
        make.right.equalTo(-10);
        make.size.equalTo(viewWidth);
    }];
}

这里相较于equalTo()方法,使用了lessThanOrEqualTo()方法,于此类似还有greaterThanOrEqualTo

- (MASConstraint * (^)(id attr))mas_equalTo; // 等于
- (MASConstraint * (^)(id attr))mas_greaterThanOrEqualTo; // 大于或等于
- (MASConstraint * (^)(id attr))mas_lessThanOrEqualTo; // 小于或等于

实例3 使用优先级进行布局

image.png

同样和实例2一样,对天蓝色的视图设置的宽度为屏幕宽度,通过调低其布局约束的优先级,动态拉低天蓝色视图的宽度。

-(void)showDemo2{
    
    UIView *view1 = [UIView new];
    view1.backgroundColor = [UIColor cyanColor];
    _v1 = view1;
    UIView *view2 = [UIView new];
    view2.backgroundColor = [UIColor greenColor];
    _v2 = view2;
    
    CGFloat screenWidth = [UIApplication sharedApplication].delegate.window.bounds.size.width;
    CGFloat viewWidth = (screenWidth - 30)/2;
    
    [self.view addSubview:view1];
    [self.view addSubview:view2];
    
    [view1 makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(10);
        make.top.equalTo(100);
        make.height.equalTo(viewWidth);
        make.width.equalTo(screenWidth).priorityLow();
    }];
    
    [view2 makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(view1.mas_right).offset(10); // 这里的mas_right不能去掉前缀mas_不然会报内存泄漏
        make.top.equalTo(view1).offset(0);
        make.right.equalTo(-10);
        make.size.equalTo(viewWidth).priorityHigh();
    }];
}

priorityLow()设置低优先级。

make.size.equalTo(viewWidth).priorityHigh(); // 高优先级
make.width.equalTo(screenWidth).priorityMedium(); // 中优先级
make.width.equalTo(screenWidth).priorityLow(); // 低优先级
make.width.equalTo(screenWidth).priority(1000); // 自定义优先级, 0~1000,1000为最高

更新和删除约束

更新原有约束的常量值

[view1 updateConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(viewWidth);
    }];

将之前所有约束都删除之后,在重新设置新的约束

[view1 remakeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(10);
        make.top.equalTo(100);
        make.height.equalTo(viewWidth);
        make.width.equalTo(screenWidth).priority(1000);
    }];
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 195,898评论 5 462
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 82,401评论 2 373
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 143,058评论 0 325
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,539评论 1 267
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,382评论 5 358
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,319评论 1 273
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,706评论 3 386
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,370评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,664评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,715评论 2 312
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,476评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,326评论 3 313
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,730评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,003评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,275评论 1 251
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,683评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,877评论 2 335

推荐阅读更多精彩内容