Masonry使用总结

Masonry使用总结


一、Masonry简介

Masonry是一个轻量级的布局框架,适用于iOS以及OS X。它用简洁的语法对官方的AutoLayout进行了封装。 Masonry有它自己的一套框架用来描述NSLayoutConstraints布局的DSL,提高了约束代码的简洁性与可读性。
Masonry现处于bugfix only状态,将不再有功能性的更新。会有更多的开发者加入Swift阵营,推荐使用Swift写的Snapkit框架来布局。

snapkit

二、导入Masonry框架

  1. 使用Cocoapods来导入框架,在使用到该框架的文件中添加主头文件:#import <Masonry/Masonry.h>
  1. 使用直接拖拽的方式拉入框架文件夹,在使用到该框架的文件中添加主头文件:#import "Masonry.h"

三、Masonry的特性

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

  2. 简化前缀的宏定义

  • 为了增加代码的可读性这里有两个简化代码的宏:#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约束添加步骤

  1. 自定义UIView
  2. 将自定义的UIView添加到父视图上。
  3. 添加约束

五、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);
    }];
Masonry动画1
// 点击屏幕移除蓝色View
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.blueView removeFromSuperview];
    [UIView animateWithDuration:1.0 animations:^{
        [self.view layoutIfNeeded];
    }];
}
Masonry动画2

解:这里的三个View的宽度是根据约束自动推断设置的,对黄色的View设置了一个与红色View有关的priority(250)的优先级,它同时有对蓝色View有个最高的优先级约束(make.left.mas_equalTo(self.blueView.mas_right).with.offset(40);)。当点击屏幕是,我将蓝色View移除,此时第二优先级就是生效。

3. Masonry官方Demo之Basic

basic1
basic2
- (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 of mas_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_remakeConstraintsmas_updateConstraints 的区别在于前者重新对视图进行了约束(抛弃了之前的约束),后者是更新约束条件(保留未更新的约束,如:这次更新了对 height 的约束,其他对X&Y以及宽的约束不变)。
重写约束1
重写约束2

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

推荐阅读更多精彩内容