Masonry仍旧在持续维护中,借助于开放社区,我们致力于修复漏洞和合并优秀的需求。然而你的项目是用Swift语言的,我们推荐使用SnapKit,因为它有着更简短的API来更好适应Swift.
Masonry是一种轻量级的布局框架,采用了更良好的语言来封装AutoLayout。Masonry有自己的布局DSL,提供了一种链式方式来描述你的NSLayoutConstraints,通过这种方式产生的布局代码更简洁,更易读。Masonry支持iOS和Mac OS X.
NSLayoutConstraints的弊端在哪?
通过底层的AutoLayout可以比较有效和灵活的组织和布局你的Views,然而通过代码创建约束比较冗长且不生动。试想这样一个例子:创建一个View距离父视图的边界都为10,代码如下:
UIView *superview = self.view;
UIView *view1 = [[UIView alloc] init];
view1.translatesAutoresizingMaskIntoConstraints = NO;
view1.backgroundColor = [UIColor greenColor];
[superview addSubview:view1];
UIEdgeInsets padding = UIEdgeInsetsMake(10, 10, 10, 10);
[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],
]];
像这种简单的例子代码都如此冗长,当你的视图复杂的时候可读性就更差了。另外一种方式可以使用VFL,代码更少点,不过这种ASCII风格的语言有它自己的弊端并且实现动画效果比较难,就比如NSLayoutConstraint constraintsWithVisualFormat:返回一个数组。
认识下MASConstraintMaker
同样的例子我们使用MASConstraintMaker来编写
UIEdgeInsets padding = UIEdgeInsetsMake(10, 10, 10, 10);
[view1 mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(superview.mas_top).with.offset(padding.top); //with is an optional semantic filler
make.left.equalTo(superview.mas_left).with.offset(padding.left);
make.bottom.equalTo(superview.mas_bottom).with.offset(-padding.bottom)