Masonry的链式调用非常的好用,那它是怎么实现的呢?
我们以- (NSArray*)mas_makeConstraints:(void(NS_NOESCAPE^)(MASConstraintMaker*make))block;为例进行分析:
[redViewmas_makeConstraints:^(MASConstraintMaker *make) {
make.left.top.equalTo(@10);
make.right.bottom.equalTo(@-10);
}];
1.mas_makeConstraints内部首先把目标视图和约束制造者进行绑定:
MASConstraintMaker *constraintMaker = [[MASConstraintMaker alloc] initWithView:self];
2.然后调用了block,把约束制作者传递了过来
block(constraintMaker);
3.添加约束
make.left.top.equalTo(@10):链式调用把需要添加的约束添加到约束制造者的数组中,之后统一进行安装,每次都返回MASConstraint对象;
4.equalTo(@-10)的用法:
equalTo(@-10)其实分为了两步,一步是返回了block,而是对block进行调用;
4.1 equalTo 会返回一个block
- (MASConstraint * (^)(id))equalTo { return ^id(id attribute) { return self.equalToWithRelation(attribute, NSLayoutRelationEqual); }; }
4.2 MASConstraint * (^)(id) 就是返回的那个block,之后进行调用;