Masonry学习总结

公司一直用的代码(自己封装的一套约束工具)和xib(autoLayout)相结合的方式来对控件进行布局和约束。本人更倾向于用纯代码布局。虽然公司封装了一套代码布局的方法,但为了更好适应其它的工作,决定开始学习使用Masonry。并记录学习的心得,与大家共享。

一.基础篇

1.Masonry下载地址下载地址。也可以用cocoaPods来管理。

2.正式开始
对这三个view进行布局

在.pch文件添加以下代码

//define this constant if you want to use Masonry without the 'mas_' prefix
    #define MAS_SHORTHAND//可不加mas前缀了

    //define this constant if you want to enable auto-boxing for default syntax
    #define MAS_SHORTHAND_GLOBALS //自动装箱

注意:添加Masonry约束前,要保证控件已经添加到父控件上了。

 UIView *greenView = UIView.new;
    greenView.backgroundColor = UIColor.greenColor;
    greenView.layer.borderColor = UIColor.blackColor.CGColor;
    greenView.layer.borderWidth = 2;
    [self addSubview:greenView];
    
    UIView *redView = UIView.new;
    redView.backgroundColor = UIColor.redColor;
    redView.layer.borderColor = UIColor.blackColor.CGColor;
    redView.layer.borderWidth = 2;
    [self addSubview:redView];
    
    UIView *blueView = UIView.new;
    blueView.backgroundColor = UIColor.blueColor;
    blueView.layer.borderColor = UIColor.blackColor.CGColor;
    blueView.layer.borderWidth = 2;
    [self addSubview:blueView];
    
    UIView *superview = self;
    int padding = 10;
    
    [greenView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.greaterThanOrEqualTo(superview.top).offset(padding);
        make.left.equalTo(superview.left).offset(padding);
        make.bottom.equalTo(blueView.top).offset(-padding);
        make.right.equalTo(redView.left).offset(-padding);
        
        make.width.equalTo(redView.width);
        make.height.equalTo(redView.height);
        make.height.equalTo(blueView.height);
    }];
    
    [redView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(superview.top).offset(padding);
        make.left.equalTo(greenView.right).with.offset(padding);//可以加with,提高可读性
        make.bottom.equalTo(blueView.top).offset(-padding);
        make.right.equalTo(superview.right).offset(-padding);
        
        make.width.equalTo(greenView);
        make.height.equalTo(@[greenView,blueView]);//可以通过数组,里面是view
        
    }];
    
    
    [blueView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(greenView.bottom).offset(padding);
        make.left.equalTo(superview.left).offset(padding);
        make.bottom.equalTo(superview.bottom).offset(-padding);
        make.right.equalTo(superview.right).offset(-padding);
        
        make.height.equalTo(@[greenView.mas_height,redView.mas_height]);
    }];//通过数组,里面是属性

运行,就能看到上面的效果图了。这是最基本的Masonry用法。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值