Masonry学习

从开始做IOS项目都是xib或者storyboard。都是增加脱线增加约束。但是网上很多别人的优秀代码,有些是Masonry约束的。为了学习别人的代码,自己也需要Masonry。

源码地址 https://github.com/SnapKit/Masonry

需要导入#import "Masonry.h"

例子1

// 初始化view并设置背景

UIView *view = [UIView new];

view.backgroundColor = [UIColor redColor];

[self.view addSubview:view];  //在做autoLayout之前 一定要先将view添加到superview上面,否则会崩溃

// 使用mas_makeConstraints添加约束

[view mas_makeConstraints:^(MASConstraintMaker *make) {

// 添加大小约束

make.size.mas_equalTo(CGSizeMake(100, 100));

// 添加居中约束(居中方式与self相同)

make.center.equalTo(self.view);

}];


例子2

// 初始化view并设置背景

UIView *view = [UIView new];

view.backgroundColor = [UIColor redColor];

[self.view addSubview:view];

// 使用mas_makeConstraints添加约束

[view mas_makeConstraints:^(MASConstraintMaker *make) {

// 添加大小约束

make.size.mas_equalTo(CGSizeMake(100, 100));

// 添加居中约束(居中方式与self相同)

make.center.equalTo(self.view);

}];

UIView *view2=[UIView new];

view2.backgroundColor=[UIColor purpleColor];

[view  addSubview:view2];

[view2 mas_makeConstraints:^(MASConstraintMaker *make) {

make.edges.equalTo(view).with.insets(UIEdgeInsetsMake(10, 10, 10, 10));

}];


例子3

// 初始化view并设置背景

UIView *view11 = [UIView new];

view11.backgroundColor = [UIColor redColor];

[self.view addSubview:view11];

// 使用mas_makeConstraints添加约束

//mas_makeConstraints就是Masonry的autolayout添加函数 将所需的约束添加到block中行了

[view11 mas_makeConstraints:^(MASConstraintMaker *make) {

//将sv居中(很容易理解吧?)

make.center.equalTo(self.view);

//将size设置成(300,300)

make.size.mas_equalTo(CGSizeMake(300, 300));

}];

int padding1=10;

UIView *view1=[UIView new];

[view1 showPlaceHolder];

view1.backgroundColor=[UIColor purpleColor];

UIView *view2=[UIView new];

view2.backgroundColor=[UIColor orangeColor];

[view2 showPlaceHolder];

[self.view addSubview:view1];

[self.view addSubview:view2];

[view1 mas_makeConstraints:^(MASConstraintMaker *make) {

make.centerY.mas_equalTo(view11.mas_centerY);

make.left.equalTo(view11.mas_left).with.offset(padding1);

make.right.equalTo(view2.mas_left).with.offset(-padding1);

make.height.mas_equalTo(@150);

make.width.equalTo(view2);

}];

[view2 mas_makeConstraints:^(MASConstraintMaker *make) {

make.centerY.mas_equalTo(view11.mas_centerY);

make.left.equalTo(view1.mas_right).with.offset(padding1);

make.right.equalTo(view11.mas_right).with.offset(-padding1);

make.height.mas_equalTo(@150);

make.width.equalTo(view1);

}];


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容