Masonry

作者: MaZengyi | 来源:发表于2017-01-19 23:52 被阅读127次

    自从苹果推出 AutoLayout 以来,它的冗长的语法被很多人诟病。导致 AutoLayout 使用度一直不高,但是 Masonry 却解决了这些痛点。

    AutoLayout 和 Masonry

    AutoLayout 很好,但是却很冗长,如一个 view 想上下左右距离父视图一些距离,如果用 AutoLayout 会是这样

    [superview addConstraints:@[
    
        //view1 constraints
        [NSLayoutConstraint constraintWithItem:view1
                                     attribute:NSLayoutAttributeTop
                                     relatedBy:NSLayoutRelationEqual
                                        toItem:superview
                                     attribute:NSLayoutAttributeTop
                                    multiplier:1.0
                                      constant:padding.top],
    
        [NSLayoutConstraint constraintWithItem:view1
                                     attribute:NSLayoutAttributeLeft
                                     relatedBy:NSLayoutRelationEqual
                                        toItem:superview
                                     attribute:NSLayoutAttributeLeft
                                    multiplier:1.0
                                      constant:padding.left],
    
        [NSLayoutConstraint constraintWithItem:view1
                                     attribute:NSLayoutAttributeBottom
                                     relatedBy:NSLayoutRelationEqual
                                        toItem:superview
                                     attribute:NSLayoutAttributeBottom
                                    multiplier:1.0
                                      constant:-padding.bottom],
    
        [NSLayoutConstraint constraintWithItem:view1
                                     attribute:NSLayoutAttributeRight
                                     relatedBy:NSLayoutRelationEqual
                                        toItem:superview
                                     attribute:NSLayoutAttributeRight
                                    multiplier:1
                                      constant:-padding.right],
    
     ]];
    

    可以看出是多么的啰嗦,但是如果用 Masonry 呢

    [view1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(superview).with.insets(padding);
    }];
    

    用了 Masonry 世界也清净了,真是一个奇妙的东西

    梳理 Masonry 类

    • MASConstraint这是对约束的封装,提供链式编程支持,约束关系(=、<=、>=),已经约束属性(NSLayoutAttributeLeft、Priority等)。将系统的布局约束封装到这个地方,这也是一个基类,并不直接使用。
    • MASViewConstraint这是MASConstraint的一个子类,这个类是对 view 布局约束的封装,除了包含了以上所说属性封装之外,它还包含了2个视图 view 的封装(MASViewAttribute),因为布局是在2个视图直接产生。
    • MASCompositeConstraintMASConstraint的另外一个子类,它的主要功能是管理一组MASConstraint对象和其子对象
    • MASViewAttribute是一个对需要布局的 view 的封装,它包含了3个东西,view:需要布局的 view,item:需要将此 view 布局到哪个对象之上,layoutAttribute布局的属性,如 NSLayoutAttributeLeft, NSLayoutAttributeRight等,在回想刚才我们说写的系统布局
     [NSLayoutConstraint constraintWithItem:view1
                                    attribute:NSLayoutAttributeTop
                                    relatedBy:NSLayoutRelationEqual
                                       toItem:superview
                                    attribute:NSLayoutAttributeTop
                                   multiplier:1.0
                                     constant:padding.top],
    
    

    那么 view 就是对应 constraintWithItem , item 对应 toItem,layoutAttribute 对应 attribute,当然其他属性都在父类中封装了。

    • MASConstraintMaker这是创建约束对象 MASConstraint 的生产类,如代码所示
    [view1 mas_makeConstraints:^(MASConstraintMaker *make) {
       make.edges.equalTo(superview).with.insets(padding);
    }];
    

    任何一个 Masonry 的约束都用此开始,由此结束,如何开始和结束我们会在下文中说。

    Masonry 工作原理

    一个最简单的约束写法

    [view1 mas_makeConstraints:^(MASConstraintMaker *make) {
       make.left.equalTo(superview.mas_left).with.offset(0);
    }];
    

    mas_makeConstraints

    mas_makeConstraints是 UIView 的分类,实现如下

    - (NSArray *)mas_makeConstraints:(void(^)(MASConstraintMaker *))block {
        self.translatesAutoresizingMaskIntoConstraints = NO;
        MASConstraintMaker *constraintMaker = [[MASConstraintMaker alloc] initWithView:self];
        block(constraintMaker);
        return [constraintMaker install];
    }
    

    创建了一个MASConstraintMaker对象,并且传递进 Block 我们就开始布局了。
    在最后调用一下install,那么install是做什么的呢,我们最后说。

    一切从 make 开始

    make 被当做起点,一个约束(MASConstraint)都是从 make 中创建出来的。部分代码如下

    @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;
    

    如 left 做了什么

        return [self addConstraintWithLayoutAttribute:NSLayoutAttributeLeft];
        
        //  addConstraintWithLayoutAttribute 方法
        - (MASConstraint *)addConstraintWithLayoutAttribute:(NSLayoutAttribute)layoutAttribute {
        return [self constraint:nil addConstraintWithLayoutAttribute:layoutAttribute];
    }
        
    

    调用了addConstraintWithLayoutAttribute方法。里面实现如下

    - (MASConstraint *)constraint:(MASConstraint *)constraint addConstraintWithLayoutAttribute:(NSLayoutAttribute)layoutAttribute {
        MASViewAttribute *viewAttribute = [[MASViewAttribute alloc] initWithView:self.view layoutAttribute:layoutAttribute];
        MASViewConstraint *newConstraint = [[MASViewConstraint alloc] initWithFirstViewAttribute:viewAttribute];
        if ([constraint isKindOfClass:MASViewConstraint.class]) {
            //replace with composite constraint
            NSArray *children = @[constraint, newConstraint];
            MASCompositeConstraint *compositeConstraint = [[MASCompositeConstraint alloc] initWithChildren:children];
            compositeConstraint.delegate = self;
            [self constraint:constraint shouldBeReplacedWithConstraint:compositeConstraint];
            return compositeConstraint;
        }
        if (!constraint) {
            newConstraint.delegate = self;
            [self.constraints addObject:newConstraint];
        }
        return newConstraint;
    }
    

    实现原理:

    1. 生成MASViewAttribute对象,此对象代表需要布局的 view 和 布局属性,
    2. 创建一个封装的布局对象MASViewConstraint,需要一个待布局的对象MASViewAttribute,并且将 delegate 设置为 。
    3. 加入 make 的 constraints的数组中。
    4. 返回 MASViewConstraint 对象

    接管者 MASViewConstraint

    在 make 放出 left,right 之后就由 MASViewConstraint 接管后面的工作了,MASViewConstraint继承了MASConstraint,也提供了,left,right 等和 equal 方法属性。如

    make.left.right
    

    这个时候做什么呢

      return [self.delegate constraint:self addConstraintWithLayoutAttribute:layoutAttribute];
    

    可以看出是调用了代理的 addConstraintWithLayoutAttribute,还记得上文提过代理是 make 么,其实也是代理到 make 的addConstraintWithLayoutAttribute。这里需要注意一个判断,在addConstraintWithLayoutAttribute实现中,有这么一个判断

     if ([constraint isKindOfClass:MASViewConstraint.class]) {
            //replace with composite constraint
            NSArray *children = @[constraint, newConstraint];
            MASCompositeConstraint *compositeConstraint = [[MASCompositeConstraint alloc] initWithChildren:children];
            compositeConstraint.delegate = self;
            [self constraint:constraint shouldBeReplacedWithConstraint:compositeConstraint];
            return compositeConstraint;
        }
    

    这个时候使用 MASCompositeConstraint 来包裹2个对象,如

    make.left.right 转换类型为 MASCompositeConstraint对象,里面包含了 [left,right],
    make.left.right.top.bottom 转换为 [[[left.right],top],bottom]
    
    

    这么实现是为了实现如下的语法结构,代码更加简洁

    make.left.right.top.bottom.equal(0)
    

    回到上文的例子

    make.left.equalTo(superview.mas_left).with.offset(0);
    

    这里直接调用了 equalTo , equalTo 是 mas_equalTo 的宏,

    #define equalTo(...)                     mas_equalTo(__VA_ARGS__)
    

    mas_equalTo 返回 block,以便继续进行链式调用。equal 中代码如下

    - (MASConstraint * (^)(id, NSLayoutRelation))equalToWithRelation {
        return ^id(id attribute, NSLayoutRelation relation) {
            if ([attribute isKindOfClass:NSArray.class]) {
                NSAssert(!self.hasLayoutRelation, @"Redefinition of constraint relation");
                NSMutableArray *children = NSMutableArray.new;
                for (id attr in attribute) {
                    MASViewConstraint *viewConstraint = [self copy];
                    viewConstraint.secondViewAttribute = attr;
                    [children addObject:viewConstraint];
                }
                MASCompositeConstraint *compositeConstraint = [[MASCompositeConstraint alloc] initWithChildren:children];
                compositeConstraint.delegate = self.delegate;
                [self.delegate constraint:self shouldBeReplacedWithConstraint:compositeConstraint];
                return compositeConstraint;
            } else {
                NSAssert(!self.hasLayoutRelation || self.layoutRelation == relation && [attribute isKindOfClass:NSValue.class], @"Redefinition of constraint relation");
                self.layoutRelation = relation;
                self.secondViewAttribute = attribute;
                return self;
            }
        };
    }
    

    实现思路为,如果是针对多个 view 来创建约束那么使用MASCompositeConstraint来包裹多个对象,否则设置第二个 view(MASViewConstraint),之前在 make.left 已经设置第一个 view 对象,表示待布局的对象,这里第二个指的是约束的参照的 view (MASViewConstraint)实现代码如下,

    - (void)setSecondViewAttribute:(id)secondViewAttribute {
        if ([secondViewAttribute isKindOfClass:NSValue.class]) {
            [self setLayoutConstantWithValue:secondViewAttribute];
        } else if ([secondViewAttribute isKindOfClass:MAS_VIEW.class]) {
            _secondViewAttribute = [[MASViewAttribute alloc] initWithView:secondViewAttribute layoutAttribute:self.firstViewAttribute.layoutAttribute];
        } else if ([secondViewAttribute isKindOfClass:MASViewAttribute.class]) {
            _secondViewAttribute = secondViewAttribute;
        } else {
            NSAssert(NO, @"attempting to add unsupported attribute: %@", secondViewAttribute);
        }
    }
    

    如果是 NSValue 对象,那么使用 2个 视图的公共父视图
    如果是 UIView 对象(MAS_VIEW 是 UIView 别名,在 iOS 上)
    如果是 MASViewAttribute 则直接当做_secondViewAttribute

    equalTo(superview.mas_left) 相等于 equalTo(0) 相等于 equalTo(superview)
    

    接下去 是 with ,with 和 and 一样,都是介词,起到连接语法的作用,

    offset 则是设置约束的值 constant value,调节偏移。

    支持一条约束已经生成了,接下去看看如何转换成 autolayout 的形式。

    开始的地方就是结束的地方

    mas_makeConstraints

    经过一串的语法下来,我们现在到了转化的过程了,在 Masonry 中称之为 install,也就是我们 make 的 install,实现代码为

    - (NSArray *)install {
        if (self.removeExisting) {
            NSArray *installedConstraints = [MASViewConstraint installedConstraintsForView:self.view];
            for (MASConstraint *constraint in installedConstraints) {
                [constraint uninstall];
            }
        }
        NSArray *constraints = self.constraints.copy;
        for (MASConstraint *constraint in constraints) {
            constraint.updateExisting = self.updateExisting;
            [constraint install];
        }
        [self.constraints removeAllObjects];
        return constraints;
    }
    

    我们忽略掉 removeExisting,可以看出是调用 MASConstraint 的 install,代码比较长,取出最核心的代码

     MAS_VIEW *firstLayoutItem = self.firstViewAttribute.item;
        NSLayoutAttribute firstLayoutAttribute = self.firstViewAttribute.layoutAttribute;
        MAS_VIEW *secondLayoutItem = self.secondViewAttribute.item;
        NSLayoutAttribute secondLayoutAttribute = self.secondViewAttribute.layoutAttribute;
    
        // alignment attributes must have a secondViewAttribute
        // therefore we assume that is refering to superview
        // eg make.left.equalTo(@10)
        if (!self.firstViewAttribute.isSizeAttribute && !self.secondViewAttribute) {
            secondLayoutItem = self.firstViewAttribute.view.superview;
            secondLayoutAttribute = firstLayoutAttribute;
        }
        
        MASLayoutConstraint *layoutConstraint
            = [MASLayoutConstraint constraintWithItem:firstLayoutItem
                                            attribute:firstLayoutAttribute
                                            relatedBy:self.layoutRelation
                                               toItem:secondLayoutItem
                                            attribute:secondLayoutAttribute
                                           multiplier:self.layoutMultiplier
                                             constant:self.layoutConstant];
        
        layoutConstraint.priority = self.layoutPriority;
        layoutConstraint.mas_key = self.mas_key;
    

    取出firstViewAttributesecondViewAttribute然后根据根据已有的参数构建MASLayoutConstraint

    mas_updateConstraints

    mas_updateConstraints可以更新约束,代码为

    
    // make 
    - (NSArray *)mas_updateConstraints:(void(^)(MASConstraintMaker *))block {
        self.translatesAutoresizingMaskIntoConstraints = NO;
        MASConstraintMaker *constraintMaker = [[MASConstraintMaker alloc] initWithView:self];
        constraintMaker.updateExisting = YES;
        block(constraintMaker);
        return [constraintMaker install];
    }
    
    // MASViewConstraint
      if (self.updateExisting) {
            existingConstraint = [self layoutConstraintSimilarTo:layoutConstraint];
        }
        if (existingConstraint) {
            // just update the constant
            existingConstraint.constant = layoutConstraint.constant;
            self.layoutConstraint = existingConstraint;
        } else {
            [self.installedView addConstraint:layoutConstraint];
            self.layoutConstraint = layoutConstraint;
            [firstLayoutItem.mas_installedConstraints addObject:self];
        }
    
    

    思路为,找到相同的约束,然后更改 constant 值

    mas_remakeConstraints

    mas_remakeConstraints可以重新生成约束,实现代码为

      if (self.removeExisting) {
            NSArray *installedConstraints = [MASViewConstraint installedConstraintsForView:self.view];
            for (MASConstraint *constraint in installedConstraints) {
                [constraint uninstall];
            }
        }
    

    调用 MASConstraint 的 uninstall 然后在重新 install

    核心实现就是如此,当然一些更详细的细节,大家可以去查看源代码。

    其他

    链式编程

    链式编程在 Masonry 中用处广泛,如以下代码

    make.edges.equalTo(superview).with.insets(padding);
    

    它不需要传统的 OC 写法 [],转而使用了跟在现代化的代用方式。那么如何实现这一原理的呢?
    当然我们可以使用点语法的时候(.xxx)有2个情况,一个是属性( @property ),一个是 Block 语法,xxx();那么看看 Masonry 怎么使用,如以下的代码

       make.edges.equalTo(superview).with.insets(padding);
    

    edges 是 make 的一个属性,可以使用点语法,

    @property (nonatomic, strong, readonly) MASConstraint *edges;
    

    equalTo 是 edges (MASConstraint)的一个 Block ,所以也可以使用点语法

    - (MASConstraint * (^)(id attr))mas_equalTo;
    

    后面的情况和前面相同,由此,我们可以根据属性和 Block 来使用点语法。

    自动装箱

    Masonry 中 equal 有2个写法

    make.top.mas_equalTo(42);
    make.top.equalTo(@42);
    

    我们可以看出区别,使用 equalTo 需要传入一个对象, 而使用 mas_equalTo 则会自动打包将原始类型打包成对象。
    在源代码中

    #define mas_equalTo(...)                 equalTo(MASBoxValue((__VA_ARGS__)))
    #define mas_greaterThanOrEqualTo(...)    greaterThanOrEqualTo(MASBoxValue((__VA_ARGS__)))
    #define mas_lessThanOrEqualTo(...)       lessThanOrEqualTo(MASBoxValue((__VA_ARGS__)))
    
    #define mas_offset(...)                  valueOffset(MASBoxValue((__VA_ARGS__)))
    
    

    mas_equalTo 是一个红,调用了 equalTo 并且使用 MASBoxValue 来打包。那么 MASBoxValue 是怎么实现的呢,以下是具体实现代码

    static inline id _MASBoxValue(const char *type, ...) {
        va_list v;
        va_start(v, type);
        id obj = nil;
        if (strcmp(type, @encode(id)) == 0) {
            id actual = va_arg(v, id);
            obj = actual;
        } else if (strcmp(type, @encode(CGPoint)) == 0) {
            CGPoint actual = (CGPoint)va_arg(v, CGPoint);
            obj = [NSValue value:&actual withObjCType:type];
        } else if (strcmp(type, @encode(CGSize)) == 0) {
            CGSize actual = (CGSize)va_arg(v, CGSize);
            obj = [NSValue value:&actual withObjCType:type];
        } else if (strcmp(type, @encode(MASEdgeInsets)) == 0) {
            MASEdgeInsets actual = (MASEdgeInsets)va_arg(v, MASEdgeInsets);
            obj = [NSValue value:&actual withObjCType:type];
        } else if (strcmp(type, @encode(double)) == 0) {
            double actual = (double)va_arg(v, double);
            obj = [NSNumber numberWithDouble:actual];
        } else if (strcmp(type, @encode(float)) == 0) {
            float actual = (float)va_arg(v, double);
            obj = [NSNumber numberWithFloat:actual];
        } else if (strcmp(type, @encode(int)) == 0) {
            int actual = (int)va_arg(v, int);
            obj = [NSNumber numberWithInt:actual];
        } else if (strcmp(type, @encode(long)) == 0) {
            long actual = (long)va_arg(v, long);
            obj = [NSNumber numberWithLong:actual];
        } else if (strcmp(type, @encode(long long)) == 0) {
            long long actual = (long long)va_arg(v, long long);
            obj = [NSNumber numberWithLongLong:actual];
        } else if (strcmp(type, @encode(short)) == 0) {
            short actual = (short)va_arg(v, int);
            obj = [NSNumber numberWithShort:actual];
        } else if (strcmp(type, @encode(char)) == 0) {
            char actual = (char)va_arg(v, int);
            obj = [NSNumber numberWithChar:actual];
        } else if (strcmp(type, @encode(bool)) == 0) {
            bool actual = (bool)va_arg(v, int);
            obj = [NSNumber numberWithBool:actual];
        } else if (strcmp(type, @encode(unsigned char)) == 0) {
            unsigned char actual = (unsigned char)va_arg(v, unsigned int);
            obj = [NSNumber numberWithUnsignedChar:actual];
        } else if (strcmp(type, @encode(unsigned int)) == 0) {
            unsigned int actual = (unsigned int)va_arg(v, unsigned int);
            obj = [NSNumber numberWithUnsignedInt:actual];
        } else if (strcmp(type, @encode(unsigned long)) == 0) {
            unsigned long actual = (unsigned long)va_arg(v, unsigned long);
            obj = [NSNumber numberWithUnsignedLong:actual];
        } else if (strcmp(type, @encode(unsigned long long)) == 0) {
            unsigned long long actual = (unsigned long long)va_arg(v, unsigned long long);
            obj = [NSNumber numberWithUnsignedLongLong:actual];
        } else if (strcmp(type, @encode(unsigned short)) == 0) {
            unsigned short actual = (unsigned short)va_arg(v, unsigned int);
            obj = [NSNumber numberWithUnsignedShort:actual];
        }
        va_end(v);
        return obj;
    }
    

    容易看出,是根据 encodeType 来判断各个数据类型,并且提供自动打包到相应的类型。

    相关文章

      网友评论

          本文标题:Masonry

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