【Objective-c】 Masonry的基本使用

Object-C :使用Masonry
Swift:使用Snapkit

Masonry 和 布局优先级约束
呆萌的中指

实例一:

masonary:约束优先级


firstExample.gif
#pragma mark - 基础使用1
- (void)firestExample{
    //红
    [_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(@50);
    }];
    //蓝
    [_blueView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(_redView.mas_right).with.offset(40);
        make.height.width.bottom.mas_equalTo(_redView);
    }];
    //黄
    [_yellowView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(_blueView.mas_right).with.offset(40);
        make.right.mas_equalTo(self.view.mas_right).with.offset(-20);
        make.height.width.bottom.mas_equalTo(_redView);
        
        //优先级
        //必须添加这个优先级,否则blueView被移除后,redView 和 yellowView 的宽度就不能计算出来
        make.left.mas_equalTo(_redView.mas_right).with.offset(20).priority(250);
    }];
    
    [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(removeBlueView:) userInfo:_blueView repeats:YES];
}

- (void)removeBlueView:(NSTimer *)timer{
    UIView *view = timer.userInfo;
    [view removeFromSuperview];
    [UIView animateWithDuration:0.3 animations:^{
        [self.view layoutIfNeeded];
    }];
}

实例二:

masonry:基本方法


Paste_Image.png
#pragma mark - 基础使用2
- (void)secondExample{
    int padding = 15;
    
    [_redView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view.mas_left).with.offset(padding);
        make.top.mas_equalTo(self.view.mas_top).with.offset(padding);
        make.bottom.mas_equalTo(_yellowView.mas_top).with.offset(-padding);
        make.width.mas_equalTo(_blueView);
    }];

    [_blueView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(_redView.mas_right).with.offset(padding);
        make.right.mas_equalTo(self.view.mas_right).with.offset(-padding);
        make.height.bottom.mas_equalTo(_redView);
    }];

    [_yellowView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view.mas_left).with.offset(padding);
        make.right.mas_equalTo(self.view.mas_right).with.offset(-padding);
        make.bottom.mas_equalTo(self.view.mas_bottom).with.offset(-padding);
        make.height.mas_equalTo(_redView);
    }];
}

实例三:

masonry : 更新约束


ThirdExample.gif
#pragma mark - 点击按钮放大
- (void)growButtonClick{
    self.growButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.growButton setTitle:@"点我放大" forState:UIControlStateNormal];
    self.growButton.layer.borderColor = [UIColor greenColor].CGColor;
    self.growButton.layer.borderWidth = 3;
    [self.growButton addTarget:self action:@selector(Click:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.growButton];
    self.scacle = 1.0;
    
    [self.growButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(self.view);
        //初始化宽,高,优先级最低
        make.width.height.mas_equalTo(100*self.scacle);
        //最大放大到整个view
        make.width.height.lessThanOrEqualTo(self.view);
    }];
    
}
- (void)Click:(UIButton *)sender{
    self.scacle += 1.0;
    //告诉self.view 约束需要更新
    [self.view setNeedsUpdateConstraints];
    //调用此方法self.view监测是否需要更新约束,若需要则更新,下面添加动画效果才起作用
    [self.view updateConstraintsIfNeeded];
    
    [UIView animateWithDuration:0.3 animations:^{
        [self.view layoutIfNeeded];
    }];
}

//重写该方法来更新约束
- (void)updateViewConstraints{
    //对于已经定义过的约束,需要更改的话,只能是使用update的方法修改才有效
    [self.growButton mas_updateConstraints:^(MASConstraintMaker *make) {
        //这里写需要更新的约束,不用更新的约束将继续存在
        //不会取代,如:其宽高小于屏幕宽高不需要重新再约束
        make.width.height.mas_equalTo(100*self.scacle);
    }];
    [super updateViewConstraints];
}

实例四:

masonry :重写约束


FourthExample.gif
#pragma mark - 收缩
/*
    注意:multipliedBy必须是对同一个控件本身,如果修改成相对其他控件会导致Crash
 */
- (void)createExpandButton{
    self.isExpanded = NO;
    self.growButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.growButton setTitle:@"点我展开" forState:UIControlStateNormal];
    self.growButton.layer.borderColor = [UIColor greenColor].CGColor;
    self.growButton.layer.borderWidth = 3;
    self.growButton.backgroundColor = [UIColor redColor];
    [self.growButton addTarget:self action:@selector(onGrowButtonTaped:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.growButton];
    [self.growButton mas_makeConstraints:^(MASConstraintMaker *make) {
        //mas_equalTo()没有写参考对象的时候,是指父视图
        make.top.left.right.mas_equalTo(0);
        make.bottom.mas_equalTo(-350);
    }];
}
- (void)onGrowButtonTaped:(UIButton *)sender{
    self.isExpanded = !self.isExpanded;
    if (!self.isExpanded) {
        [self.growButton setTitle:@"点我展开" forState:UIControlStateNormal];
    }else{
        [self.growButton setTitle:@"点我收起" forState:UIControlStateNormal];
    }
    [self.view setNeedsUpdateConstraints];
    [self.view updateConstraintsIfNeeded];
    [UIView animateWithDuration:0.3 animations:^{
        [self.view layoutIfNeeded];
    }];
}

- (void)updateViewConstraints{
    //这里使用update也能实现效果
    //remake会将之前的全部移除,然后重新添加
    __weak typeof(self) weakself = self;
    [self.growButton mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.mas_equalTo(0);
        //这里重写全部约束,之前的约束都将无效
        if (weakself.isExpanded) {
            make.bottom.mas_equalTo(0);
        }else{
            make.bottom.mas_equalTo(-350);
        }
    }];
    [super updateViewConstraints];
}

实例五:

masonry :比例


Paste_Image.png
#pragma mark - 比例
- (void)multipliedBy{
    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_remakeConstraints:^(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);
        //宽是高的3倍
        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);
        //高是宽的3倍
        make.height.mas_equalTo(bottomInnerView.mas_width).multipliedBy(3);
        make.center.mas_equalTo(bottomView);
    }];
}

完整Demo

================2016 12 26 补充=================
1、约束方法的简写,避免出现错误

//比如第一个例子:
[_redView mas_makeConstraints:^(MASConstraintMaker *make) { 
      make.left.mas_equalTo(self.view.mas_left).with.offset(20); 
      //可以改为:make.left.mas_equalTo(self.view.mas_left).offset(20)
      //虽然只是少了一个with,但是会减少很多bug,因为经常会出现把with打为
      //width,代码又没有报错误,但是运行了就崩溃,就很难找到问题所在了
      make.bottom.mas_equalTo(self.view.mas_bottom).with.offset(-80); 
      make.height.equalTo(@50); 
}];

2、Masonry关于UILabel的约束

宽度自适应:UILabel 的内容宽度是根据内容而定,并且是单行显示,可以设置uilabel 的抗压和抗拉属性
//1、宽度不够时
[_label1 setContentCompressionResistancePriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisHorizontal];
//2、宽度够时
[label setContentHuggingPriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisHorizontal];

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

推荐阅读更多精彩内容