美文网首页
Masonry使用

Masonry使用

作者: 暖光照 | 来源:发表于2016-10-06 23:07 被阅读0次

    简介

    Masonry是一个轻量级的布局框架,为一个view设置一定的约束,自动计算设置frame。

    用法

    //创建viw,并添加到父view上。 
    _view1=[UIView new];
    [self.view addSubview:_view1];
    
    //添加约束(必须在addSubview之后)
    [_view1 mas_makeConstraints:^(MASConstraintMaker *make) {
        //这里写约束
    }];
    

    方法

    //添加约束
    [_view1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view);
        make.size.mas_equalTo(CGSizeMake(100, 100));
    }];
    
    //更新约束(已存在的更新,未存在添加)
    [_view1 mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(@100);   //更新top的约束
        make.left.equalTo(@100);  //添加left的约束 ,size的约束不变
    }];
    
    //移除之前的约束,并添加新的约束
    [_view1 mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.view);
        make.size.mas_equalTo(CGSizeMake(150, 150));
    }];
    

    约束写法

    //设置距离父容器上下左右的边距(可为负)。
    make.edges.mas_offset(UIEdgeInsetsMake(10, 10, 10, 10));
    
    //设置中心与weakself.view的中心相等。
    make.center.equalTo(self.view);
    
    //with.offset(x)   设置偏移量(+x)。
    make.top.equalTo(self.view1).with.offset(20);
    
     //multipliedBy(x)   设置倍数(*x)。
     make.center.equalTo(self.view).multipliedBy(0.5);
    
     //设置left和top为100。
     make.left.and.top.equalTo(@100);
    

    属性

    @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; //文本基线     
    

    补充

    and和with可以省略,其源码为:
    - (MASConstraint *)with {
    return self;
    }

    - (MASConstraint *)and {
    return self;
    }  
    

    例如:

     make.left.and.top.equalTo(_view1).with.offset(10);
     //可写为
     make.left.top.equalTo(_view1).offset(10);
    

    leading与left,trailing与right 在正常情况下是等价的。在一些从右至左的布局中可能会对调。国内用left,right即可。

    相关文章

      网友评论

          本文标题:Masonry使用

          本文链接:https://www.haomeiwen.com/subject/tgoeyttx.html