Masonry仍积极维护,我们致力于修复bug和合并优质PRs来自更广泛的社区。
但是如果你使用swift在你的项目中,我们建议使用SnapKit因为它为更好的类型安全提供了一个简单的API。
Masonry是一个轻量级的布局框架封装自动布局与更好的语法。
Masonry有它自己的布局DSL提供证明的方式描述NSLayoutConstraints导致布局代码更简洁易读。Masonry支持iOS和Mac OS X。
What's wrong with NSLayoutConstraints?
在自动布局的强大和灵活的方式下组织和阐明你的观点。然而从冗长的代码创建约束和不描述。想象一下一个简单的例子,你想拥有一个视图填补它的父视图但插图10像素UIView *superview = self;
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],
]];
即使这样一个简单的示例代码需要非常详细的,很快就会变得不可读的时候你有超过2或3的观点。另一个选择是使用视觉形式语言(VFL)。然而ASCII类型语法有其自身的缺陷及其也有点难以动画NSLayoutConstraint constraintsWithVisualFormat:返回一个数组。
Prepare to meet your Maker!
这是使用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);
make.right.equalTo(superview.mas_right).with.offset(-padding.right);
}];
甚至更短
[view1 mas_makeConstraints:^(MASConstraintMaker *make) { make.edges.equalTo(superview).with.insets(padding); }];还要注意在第一个示例中我们必须约束添加到父视图([ super addConstraints:.... Masnry然而将自动添加约束到适当的视图
Masonry 也会调用
view1.translatesAutoresizingMaskIntoConstraints = NO;
.equalTo equivalent to NSLayoutRelationEqual
.lessThanOrEqualTo equivalent to NSLayoutRelationLessThanOrEqual
.greaterThanOrEqualTo equivalent to NSLayoutRelationGreaterThanOrEqual
这三个等式约束接受一个参数,可以有下列:
1. MASViewAttribute
make.centerX.lessThanOrEqualTo(view2.mas_left);
MASViewAttribute | NSLayoutAttribute |
---|---|
view.mas_left | NSLayoutAttributeLeft |
view.mas_right | NSLayoutAttributeRight |
view.mas_top | NSLayoutAttributeTop |
view.mas_bottom | NSLayoutAttributeBottom |
view.mas_leading | NSLayoutAttributeLeading |