Masonry使用归纳总结

作者: FanChason | 来源:发表于2017-03-29 13:51 被阅读917次

    前言

    Masonry 源码:https://github.com/Masonry/Masonry
    Masonry是一个轻量级的布局框架,拥有自己的描述语法,采用更优雅的链式语法封装自动布局,简洁明了,并具有高可读性,而且同时支持 iOS 和 Max OS X。

    总结

    1,基本使用

    添加约束

    • mas_makeConstraints: 只负责添加约束 AutoLayout不能同时存在两条针对同一对象的约束否则会报错
    • mas_updateConstraints: 针对上面的情况 会更新在block中出现的约束 不会导致出现两个相同约束的情况
    • mas_remakeConstraints: 清除之前所有的约束只保留新的约束

    注意:三种函数要配合使用
    使用mas_makeConstrains方法的元素必须事先添加到父视图中

    其它

    • mas_equalTo和equalTo区别:前者比后者多了类型转换操作,支持CGSize CGPoint NSNumber UIEdgeinsets。mas_equalTo是equalTo的封装,equalTo适用于基本数据类型,而mas_equaalTo适用于类似UIEdgeInsetsMake 等复杂类型,基本上它可以替换equalTo。
    举例比较:
    Make.left.equalTo(@64) 可以这么写才可以 字面量
    make.left.mas_equalTo(64); 而mas_equalTo可以不用字面量
    
    • 上左为正,下右为负: 是因为坐标而来的 视图坐标左上为原点 X向右为正 Y向下为正
    • priorityLow():设置约束优先级
    • #define MAS_SHORTHAND_GLOBALS:使用全局宏定义(需要放在.pch文件中),可以使equalTo- 等效于mas_equalTo
    • #define MAS_SHORTHAND:使用全局宏定义(需要放在.pch文件中), 可以在调用masonry方法的时候不使用mas_前缀
    // 这里注意到一个地方,就是当使用了这个全局宏定义之后,发现可以有个类`NSArray+MASAdditions.h`,看了之后发现可以
    self.buttonViews = @[ raiseButton, lowerButton, centerButton ];
    // 之后可以在updateConstraints 方法中
    -(void)updateConstraints {
       [self.buttonViews updateConstraints:^(MASConstraintMaker *make) {
            //make.baseline.equalTo(self.mas_centerY).with.offset(self.offset);
           make.center.mas_equalTo(self.view);
        }];
        [super updateConstraints];  
    }
    

    2,mas_topLayoutGuide 和 mas_bottomLayoutGuide

    // self是一个控制器
    
    // 两种效果不同
    make.top.equalTo(self.view);// 这样写效果是 topView 与 状态栏的y值相等
    make.top.equalTo(self.mas_topLayoutGuide);
    
    // 此时两种效果相同
    make.bottom.equalTo(self.mas_bottomLayoutGuide);
    make.bottom.equalTo(self.view);
    

    3,requiresConstraintBasedLayout

    如果你把一个View的所有的约束建立在updateconstraints,
    你可能永远不会得到updateconstraints的约束。
    若要解决此问题,请重写requiresConstraintBasedLayout返回YES,
    如果视图窗口需要使用基于约束的布局

    + (BOOL)requiresConstraintBasedLayout
    {
        return YES;
    }
    

    4,setNeedsUpdateConstraints,updateConstraintsIfNeeded,setNeedsLayout,layoutIfNeeded,setNeedsDisplay等方法小结

    单独成文

    5, multipliedBy和dividedBy

    • multipliedBy属性:表示约束值为约束对象的乘因数
    • dividedBy属性:表示约束值为约束对象的除因数

    可用于设置view的宽高比
    使用multipliedBy必须是对同一个控件本身

    [self.topInnerView mas_makeConstraints:^(MASConstraintMaker *make) {
                //make.width.equalTo(self.topInnerView.mas_height).multipliedBy(3);// 宽高比1.0/3.0
            make.width.equalTo(self.topInnerView.mas_height).dividedBy(3);// 宽高比3.0/1.0
    
           make.width.and.height.lessThanOrEqualTo(self.topView);
           make.width.and.height.equalTo(self.topView).with.priorityLow();
           make.center.equalTo(self.topView);
    }];
    

    6, 动态修改视图约束:

    // 创建视图约束
    [blueView mas_makeConstraints:^(MASConstraintMaker *make) {
          //self.animatableConstraint = make.edges.equalTo(superview).insets(paddingInsets).priorityLow();
          self.animatableConstraint = make.edges.equalTo(superview).insets(paddingInsets);
    ]];
    
    // 更改约束 (另一处方法中)
    UIEdgeInsets paddingInsets = UIEdgeInsetsMake(padding, padding, padding, padding);
    self.animatableConstraint.insets = paddingInsets;
    [UIView animateWithDuration:1.0 animations:^{
           [self.view layoutIfNeeded];
    }];
    

    7, debug模式:

    // 对某个view添加key值
    greenView.mas_key = @"greenView";
    // 或者如下顺序
    MASAttachKeys(greenView, redView, blueView, superview);
    // 同样的对每条约束亦可以添加key
    make.height.greaterThanOrEqualTo(@5000).key(@"ConstantConstraint");
    

    eg:
    便于定位具体哪个约束

        [greenBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.view).insets(paddingInsets);
            make.width.equalTo(@200).key(@"greenBtn__ConstantConstraint");
        }];
        
    

    打印:


    Snip20170222_1.png

    8, preferredMaxLayoutWidth: 多行label的约束问题

    // 已经确认好了位置
    // 在layoutSubviews中确认label的preferredMaxLayoutWidth值
    -(void)layoutSubviews {
        [super layoutSubviews];
        // 你必须在 [super layoutSubviews] 调用之后,longLabel的frame有值之后设置preferredMaxLayoutWidth
        self.longLabel.preferredMaxLayoutWidth = self.frame.size.width-100;
        // 设置preferredLayoutWidth后,需要重新布局
        [super layoutSubviews];
    }
    

    9, scrollView使用约束的问题:

    原理是通过一个contentView来约束scrollView的contentSize大小,也就是说以子控件的约束条件,来控制父视图的大小

    // 1. 控制scrollView大小(显示区域)
    [self.scrollView makeConstraints:^(MASConstraintMaker *make) {
         make.edges.equalTo(self.view);
    }];
    // 2. 添加一个contentView到scrollView,并且添加好约束条件
    [contentView makeConstraints:^(MASConstraintMaker *make) {
         make.edges.equalTo(self.scrollView);
         // 注意到此处的宽度约束条件,这个宽度的约束条件是比添加项
         make.width.equalTo(self.scrollView);
    }];
    // 3. 对contentView的子控件做好约束,达到可以控制contentView的大小
    

    10, 2个或2个以上的控件等间隔排序

    注释:

    /**
     *  多个控件固定间隔的等间隔排列,变化的是控件的长度或者宽度值
     *
     *  @param axisType        轴线方向
     *  @param fixedSpacing    间隔大小
     *  @param leadSpacing     头部间隔
     *  @param tailSpacing     尾部间隔
     */
    - (void)mas_distributeViewsAlongAxis:(MASAxisType)axisType 
                        withFixedSpacing:(CGFloat)fixedSpacing l
                              eadSpacing:(CGFloat)leadSpacing 
                             tailSpacing:(CGFloat)tailSpacing;
    
    /**
     *  多个固定大小的控件的等间隔排列,变化的是间隔的空隙
     *
     *  @param axisType        轴线方向
     *  @param fixedItemLength 每个控件的固定长度或者宽度值
     *  @param leadSpacing     头部间隔
     *  @param tailSpacing     尾部间隔
     */
    - (void)mas_distributeViewsAlongAxis:(MASAxisType)axisType 
                     withFixedItemLength:(CGFloat)fixedItemLength 
                             leadSpacing:(CGFloat)leadSpacing 
                             tailSpacing:(CGFloat)tailSpacing;
    

    eg: masonry官方Demo

    //  创建水平排列图标 
    //  arr: 中放置了2个或连个以上的初始化后的控件
    //  type: 0~3,四种举例
        switch (type) {
            case 0:
                [arr mas_distributeViewsAlongAxis:MASAxisTypeHorizontal withFixedSpacing:20 leadSpacing:5 tailSpacing:5];
                [arr makeConstraints:^(MASConstraintMaker *make) {
                    make.top.equalTo(@60);
                    make.height.equalTo(@60);
                }];
                break;
            case 1:
                [arr mas_distributeViewsAlongAxis:MASAxisTypeVertical withFixedSpacing:20 leadSpacing:5 tailSpacing:5];
                [arr makeConstraints:^(MASConstraintMaker *make) {
                    make.left.equalTo(@0);
                    make.width.equalTo(@60);
                }];
                break;
            case 2:
                [arr mas_distributeViewsAlongAxis:MASAxisTypeHorizontal withFixedItemLength:30 leadSpacing:200 tailSpacing:30];
                [arr makeConstraints:^(MASConstraintMaker *make) {
                    make.top.equalTo(@60);
                    make.height.equalTo(@60);
                }];
                break;
            case 3:
                [arr mas_distributeViewsAlongAxis:MASAxisTypeVertical withFixedItemLength:30 leadSpacing:30 tailSpacing:200];
                [arr makeConstraints:^(MASConstraintMaker *make) {
                    make.left.equalTo(@0);
                    make.width.equalTo(@60);
                }];
                break;
                
            default:
                break;
                
        }
    
    

    11,如果想要约束变换之后实现动画效果,则需要执行如下操作

    // 通知需要更新约束,但是不立即执行
    [self setNeedsUpdateConstraints];
    // 立即更新约束,以执行动态变换
    // update constraints now so we can animate the change
    [self updateConstraintsIfNeeded];
    // 执行动画效果, 设置动画时间
    [UIView animateWithDuration:0.4 animations:^{
       [self layoutIfNeeded];
    }];
    

    测试Demo:XCMasonryDemo
    参考延伸:
    Masonry使用注意篇
    Masonry初探
    Masonry 比例(multipliedBy)

    相关文章

      网友评论

      • 舒马赫:Masory写的很棒,但是不喜欢纯代码写界面,太慢了,另外由于autolayout先天原因布局速度是比较慢的,会影响帧率。推荐使用xml的布局库FlexLib,采用前端布局标准flexbox(不使用autolayout),支持热刷新,自动计算高度等。可以到这里了解详细信息:

        https://github.com/zhenglibao/FlexLib

      本文标题:Masonry使用归纳总结

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