1.什么是Masonry
Masonry是一个对系统NSLayoutConstraint进行封装的第三方自动布局框架,
采用链式编程的方式提供给开发者API。系统AutoLayout支持的操作,Masonry都支持,
相比系统API功能来说,Masonry是有过之而无不及。
Masonry采取了链式编程的方式,代码理解起来非常清晰易懂,而且写完之后代码量看起来非常少。
之前用NSLayoutConstraint写很多代码才能实现的布局,用Masonry最少一行代码就可以搞定。
下面看到Masonry的代码就会发现,太简单易懂了。
2.Masonry中的坑
1.在使用Masonry进行约束时,有一些是需要注意的。
2.在使用Masonry添加约束之前,需要在addSubview之后才能使用,否则会导致崩溃。
3.在添加约束时初学者经常会出现一些错误,约束出现问题的原因一般就是两种:约束冲突和缺少约束。对于这两种问题,可以通过调试和log排查。
4.之前使用Interface Builder添加约束,如果约束有错误直接就可以看出来,并且会以红色或者黄色警告体现出来。而Masonry则不会直观的体现出来,而是以运行过程中崩溃或者打印异常log体现,所以这也是手写代码进行AutoLayout的一个缺点。
3.Masonry基础API:
mas_makeConstraints() 添加约束
mas_remakeConstraints() 移除之前的约束,重新添加新的约束
mas_updateConstraints() 更新约束
equalTo() 参数是对象类型,一般是视图对象或者mas_width这样的坐标系对象
mas_equalTo() 和上面功能相同,参数可以传递基础数据类型对象,可以理解为比上面的API更强大
width() 用来表示宽度,例如代表view的宽度
mas_width() 用来获取宽度的值。和上面的区别在于,一个代表某个坐标系对象,一个用来获取坐标系对象的值
4.一些基本使用
edges
//make top,left,bottom,right equal view2
make.edges.equalTo(view2)
//make top = superview.top+5,left =superview.left+10
//bottom=superview.bottom-15,right=superview.right-20
make.edges.equalTo(superview).insets(UIEdgeInsetsmake(5,10,15,20))
size
//make width and height greater than or equalto titleLabel
make.size.greaterThanOrEqualTo(titleLabel)
//make width = superview.width+100,height =superview.height -50
make.size.equalTo(superview).sizeOffset(CGSizeMake(100,-50));
center
//make centerX and centerY = button1
make.center.equalTo(button1)
//make centerX = superview.centerX-5,centerY =superview.centerY +10
make.center.equalTo(superview).centerOffset(CGPointMake(-5,10));
你可以连接属性来增加可读性:
//All edges but the top should equal those ofthe superview
make.left.right.and.bottom.equalTo(superview);
make.top.equalTo(otherView);
5.Where should I create my constraints?应该在什么地方创建我的约束呢?
@implementation DIYCustomView
- (id)init {
self = [super init];
if (!self) return nil;
// --- Create your views here ---
self.button = [[UIButton alloc] init];
return self;
}
// tell UIKit that you are using AutoLayout
+ (BOOL)requiresConstraintBasedLayout {
return YES;
}
// this is Apple's recommended place for adding/updating constraints
- (void)updateConstraints {
// --- remake/update constraints here
[self.button remakeConstraints:^(MASConstraintMaker *make) {
make.width.equalTo(@(self.buttonSize.width));
make.height.equalTo(@(self.buttonSize.height));
}];
//according to apple super should be called at end of method
[super updateConstraints];
}
- (void)didTapButton:(UIButton *)button {
// --- Do your changes ie change variables that affect your layout etc ---
self.buttonSize = CGSize(200, 200);
// tell constraints they need updating
[self setNeedsUpdateConstraints];
}
@end
6.注意
Masonry支持CocoaPods,可以直接通过podfile文件进行集成,需要在CocoaPods中添加下面代码:
pod 'Masonry'
// 定义这个常量,就可以不用在开发过程中使用"mas_"前缀。
#define MAS_SHORTHAND
// 定义这个常量,就可以让Masonry帮我们自动把基础数据类型的数据,自动装箱为对象类型。
#define MAS_SHORTHAND_GLOBALS
文章摘自官方文档和参考网上,附上一篇Masonry详解:http://www.cocoachina.com/ios/20170109/18538.html
Masonry官方文档Github地址:https://github.com/SnapKit/Masonry
网友评论