平时代码中的视图经常要用CGRectMake(CGFloat x, CGFloat y, CGFloat width, CGFloat height);来布局,不仅代码繁多不好计算而且屏幕适配也很麻烦,这时候就我推荐使用布局框架Masonry,这样可以优化自己的代码,是布局更加简单和简洁。
Masonry is a light-weight layout framework which wraps AutoLayout with a nicer syntax. Masonry has its own layout DSL which provides a chainable way of describing your NSLayoutConstraints which results in layout code that is more concise and readable.(Masonry supports iOS and Mac OS X.)
Masonry是一个封装了AutoLayout拥有更出色句法的轻量级布局框架。Masonry有它独有的描述你自己NSLayoutConstraints的链式方法的布局DSL,这个让布局编码变得更加的简洁和更具有可读性。(Masonry同时支持iOS和Mac OS X)
Masonry下载地址:https://github.com/SnapKit/Masonry
基本使用方法:
下面我用几个例子来说明下Masonry框架的使用方法:
1、
- (void)viewDidLoad {
[super viewDidLoad];
UIView *view1 = [[UIView alloc] init];
view1.backgroundColor = [UIColor blueColor];
//使用 mas_makeConstraints方法的元素必须事先添加到父元素的中
[self.view addSubview:view1];
//mas_makeConstraints 只负责新增约束 Autolayout不能同时存在两条针对于同一对象的约束 否则会报错
[view1 mas_makeConstraints:^(MASConstraintMaker *make) {
//将view1居中
make.center.equalTo(self.view);
//将size设置成(300,300)
make.size.mas_equalTo(CGSizeMake(200, 200));
}];
运行截图如下:
2、
- (void)viewDidLoad {
[super viewDidLoad];
UIView *view1 = [[UIView alloc] init];
view1.backgroundColor = [UIColor blueColor];
[self.view addSubview:view1];
[view1 mas_makeConstraints:^(MASConstraintMaker *make) {
make.center.equalTo(self.view);
make.size.mas_equalTo(CGSizeMake(200, 200));
}];
UIView *view2 = [[UIView alloc] init];
view2.backgroundColor = [UIColor greenColor];
[self.view addSubview:view2];
[view2 mas_makeConstraints:^(MASConstraintMaker *make) {
//view2小于view1,边距为10
make.top.equalTo(view1).with.offset(10);
make.left.equalTo(view1).with.offset(10);
make.right.equalTo(view1).with.offset(-10);
make.bottom.equalTo(view1).with.offset(-10);
//这样写也可以
//make.edges.equalTo(view1).with.insets(UIEdgeInsetsMake(10, 10, 10, 10));
}];
}
运行截图:
3、设置边距,宽度不用设置,自动计算
UIView *view3 = [[UIView alloc] init];
view3.backgroundColor = [UIColor yellowColor];
[self.view addSubview:view3];
UIView *view4 = [[UIView alloc] init];
view4.backgroundColor = [UIColor yellowColor];
[self.view addSubview:view4];
[view3 mas_makeConstraints:^(MASConstraintMaker *make) {
make.centerY.equalTo(self.view);
make.right.equalTo(view4.mas_left).with.offset(-10);
make.left.equalTo(self.view.mas_left).with.offset(10);
make.height.equalTo(@150);
make.width.equalTo(view4);
}];
[view4 mas_makeConstraints:^(MASConstraintMaker *make) {
make.centerY.equalTo(self.view);
make.right.equalTo(self.view.mas_right).with.offset(-10);
make.left.equalTo(view3.mas_right).with.offset(10);
make.height.equalTo(@150);
make.width.equalTo(view3);
}];
运行截图如下:
以上就是Masonry的一些基本用法,Masonry的链式语言简洁易懂,用法也很简单,能够节省大量的开发和学习时间,非常推荐使用~~