Masonry框架的优点
Masonry是iOS在控件布局中经常使用的一个轻量级框架,Masonry让NSLayoutConstraint使用起来更为简洁。
基于NSLayoutConstraint的布局实现subView.top = superView.top * 1 + 10
subView.translatesAutoresizingMaskIntoConstraints = NO;//关闭自动布局
NSLayoutConstraint *constraint= [NSLayoutConstraint constraintWithItem:subView attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:superView attribute:NSLayoutAttributeTop multiplier:1.0f constant:10.0f];
[subView addConstraint:constraint];
基于Masonry的布局实现subView.top = superView.top * 1 + 10
[superView addSubView:subView];//必须先把view添加到父view才能使用Masonry的布局
[subView mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(@10);//3种写法
//make.top.equalTo(superView.mas_top).offset(10);
//make.top.equalTo(superView.mas_top).multipliedBy(1).offset(10);
}];
可以看到Masonry极大的简化了布局代码,用起来非常方便。
Masonry框架的类结构
1.View+MASAdditions分类介绍(左边红框中的部分)
View+MASAdditions的部分,在该分类中添加了类型为MASViewAttribute的成员属性。
- (MASViewAttribute *)mas_left {
return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeLeft];
}
- (MASViewAttribute *)mas_top {
return [[MASViewAttribute alloc] initWithView:self layoutAttribute:NSLayoutAttributeTop];
}
······
mas_left = self + NSLayoutAttributeLeft, mas_top = self +NSLayoutAttributeTop, 当然此处的self就代表当前视图。
还添加了3个公有的方法:
-
mas_makeConstraints方法负责创建安装约束
-
mas_updateConstraints负责更新已经存在的约束(若约束不存在就Install)
-
mas_remakeConstraints方法则负责移除原来已经创建的约束并添加上新的约束。
-
其他两个方法内部的实现与mas_makeConstraints类似,就是多了一个属性的设置。//返回一个数组,数组中所存放的就是当前视图中所添加的所有约束。 - (NSArray *)mas_makeConstraints:(void(^)(MASConstraintMaker *))block { //关闭自动添加约束,我们要手动添加约束 self.translatesAutoresizingMaskIntoConstraints = NO; //MASConstraintMaker类是一个工厂类,负责创建MASConstraint类型的对象(依赖于MASConstraint接口,而不依赖于具体实现)。 MASConstraintMaker *constraintMaker = [[MASConstraintMaker alloc] initWithView:self]; //给maker中的成员属性赋值 block(constraintMaker); return [constraintMaker install]; }
mas_updateConstraints中将constraintMaker中的updateExisting设置为YES
mas_remakeConstraints中所做的事情是将removeExisting属性设置成YES