Masonry

自从苹果推出 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 来判断各个数据类型,并且提供自动打包到相应的类型。

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

推荐阅读更多精彩内容