快速开始
Masonry 是一个轻量级的布局框架,用更简洁的语法封装了 AutoLayout。它提供了链式 DSL 来描述 NSLayoutConstraints,使布局代码更加简洁易读。
为什么选择 Masonry?
使用原生 NSLayoutConstraint API 创建约束非常冗长且难以阅读:
[superview addConstraints:@[
[NSLayoutConstraint constraintWithItem:view1
attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationEqual
toItem:superview
attribute:NSLayoutAttributeTop
multiplier:1.0
constant:padding.top],
// ... 仅四条边就需要更多约束
]];
使用 Masonry,同样的布局只需一行代码:
::: code-group
[view1 mas_makeConstraints:^(MASConstraintMaker *make) {
make.edges.equalTo(superview).with.insets(padding);
}];
view.mas.makeConstraints { make in
make.edges.equalTo(superview).inset(padding)
}
:::
Masonry 还会自动处理 translatesAutoresizingMaskIntoConstraints 和约束安装。
快速示例
以下是一个完整的示例,将视图固定到父视图并添加内边距:
::: code-group
UIEdgeInsets padding = UIEdgeInsetsMake(10, 10, 10, 10);
[view1 mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(superview.mas_top).with.offset(padding.top);
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);
}];
let padding = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
view.mas.makeConstraints { make in
make.top.equalTo(superview.mas.top).offset(padding.top)
make.left.equalTo(superview.mas.left).offset(padding.left)
make.bottom.equalTo(superview.mas.bottom).offset(-padding.bottom)
make.right.equalTo(superview.mas.right).offset(-padding.right)
}
:::