今天终于要对Masonry下手了, 看了一上午Masonry源码, 断点跟踪调试,下午开始写心得体会。😀
放上连接 Masonry
与SnapKit是一个作者。 一个Swift版本一个OC版本;
核心类说明
- 首先是
UIView
的分类UIView+MASAdditions
这个类包含了我们经常使用的添加约束 更新约束 的方法,还有一些扩展的属性, 这个分类也是我研究源码的入口点,
/**
* following properties return a new MASViewAttribute with current view and appropriate NSLayoutAttribute
*/
@property (nonatomic, strong, readonly) MASViewAttribute *mas_left;
@property (nonatomic, strong, readonly) MASViewAttribute *mas_top;
- (NSArray *)mas_makeConstraints:(void(NS_NOESCAPE ^)(MASConstraintMaker *make))block;
- (NSArray *)mas_updateConstraints:(void(NS_NOESCAPE ^)(MASConstraintMaker *make))block;
- (NSArray *)mas_remakeConstraints:(void(NS_NOESCAPE ^)(MASConstraintMaker *make))block;
- 接着是
MASConstraintMaker
类,这个类使用了运用工厂方法设计模式, 主要通过属性的getter
方法生成MASViewConstraint
约束对象。
/**
* Provides factory methods for creating MASConstraints.
* Constraints are collected until they are ready to be installed
*
*/
@interface MASConstraintMaker : NSObject
MASConstraint
约束的基类,封装了约束通用的方法,并提供了高层抽象方法,供子类去自实现。Masonry不直接使用此类, 使用它的子类MSAViewConstraint
和MASCompositeConstraint
;MSAViewConstraint
这个类封装了@interface MASLayoutConstraint : NSLayoutConstraint
, 最终产生最后的NSLayoutConstraint
,并装载到视图上MASCompositeConstraint
对MSAViewConstraint
的组合, 数组形式维护一组约束,当使用make.left.top
这样的代码时, 会产生一组约束对象并用MASCompositeConstraint
对象来管理;MASViewAttribute
该类负责保存需要约束布局的视图以及约束信息,封装了MASConstraint
所需元素的封装,包括view、layoutAttribute等关键元素。MASLayoutConstraint
类简单的继承了系统的NSLayoutConstraint
,增加了一个mas_key
属性, 用于标识约束对象, 方便Debug调试;
@interface MASLayoutConstraint : NSLayoutConstraint
/**
* a key to associate with this constraint
*/
@property (nonatomic, strong) id mas_key;
@end
核心代码解析
- 在日常布局view,我们会经常这么写
[redView mas_makeConstraints:^(MASConstraintMaker *make) {
make.left.equalTo(self.view.mas_left).offset(100);
make.top.equalTo(self.view.mas_top).offset(100);
make.size.mas_equalTo(CGSizeMake(100, 100));
}];
}
- 通过
UIView
的分类,去调用这个方法, 通过调用者view
初始化一个MASConstraintMaker
的工厂对象,通过工厂对象,去生成各种约束实例;
- (NSArray *)mas_makeConstraints:(void(^)(MASConstraintMaker *))block {
// 禁用自动布局,使手动布局生效
self.translatesAutoresizingMaskIntoConstraints = NO;
// 创建工厂对象
MASConstraintMaker *constraintMaker = [[MASConstraintMaker alloc] initWithView:self];
// 通过工厂类生成相应的约束对象
block(constraintMaker);
// 安装约束对象并返回数组
return [constraintMaker install];
}
- 通过工厂对象
make
去调用left,简单了调用了另一个方法
- (MASConstraint *)left {
return [self addConstraintWithLayoutAttribute:NSLayoutAttributeLeft];
}
- 该方法什么也没做,调用了另一个方法,接着往下走。
- (MASConstraint *)addConstraintWithLayoutAttribute:(NSLayoutAttribute)layoutAttribute {
return [self constraint:nil addConstraintWithLayoutAttribute:layoutAttribute];
}
- 这个方法使用一个之前保存的
view
和layoutAttribute
初始化创建一个viewAttribute
,在用这个保存着视图以及布局信息的对象去创建一个newConstraint
,因为constraint
是nil
,所以把这个约束对象加到constraints
中; 接着返回一个MASViewConstraint
对象;
- (MASConstraint *)constraint:(MASConstraint *)constraint addConstraintWithLayoutAttribute:(NSLayoutAttribute)layoutAttribute {
MASViewAttribute *viewAttribute = [[MASViewAttribute alloc] initWithView:self.view layoutAttribute:layoutAttribute];
MASViewConstraint *newConstraint = [[MASViewConstraint alloc] initWithFirstViewAttribute:viewAttribute];
if ([constraint isKindOfClass:MASViewConstraint.class]) {
//replace with composite constraint
NSArray *children = @[constraint, newConstraint];
MASCompositeConstraint *compositeConstraint = [[MASCompositeConstraint alloc] initWithChildren:children];
compositeConstraint.delegate = self;
[self constraint:constraint shouldBeReplacedWithConstraint:compositeConstraint];
return compositeConstraint;
}
if (!constraint) {
newConstraint.delegate = self;
[self.constraints addObject:newConstraint];
}
return newConstraint;
}
6.返回的MASViewConstraint
对象去调用父类MASConstraint
方法
父类提供了俩个equalTo方法, 因为Masonry提供了MAS_SHORTHAND
宏, 所以父类提供俩种命名的方法,方便风格统一;
在导入#import <Masonry/Masonry.h>
头文件前,定义MAS_SHORTHAND
宏,可以使用无mas_
前缀版本
- (MASConstraint * (^)(id))equalTo {
return ^id(id attribute) {
return self.equalToWithRelation(attribute, NSLayoutRelationEqual);
};
}
- (MASConstraint * (^)(id))mas_equalTo {
return ^id(id attribute) {
return self.equalToWithRelation(attribute, NSLayoutRelationEqual);
};
}
- 调用
equalTo
返回一个MASConstraint * (^)(id)
Block , 在其内部调用了它的子类MSAViewConstraint
重写的equalToWithRelation
方法
MASConstraint
的方法
- (MASConstraint * (^)(id, NSLayoutRelation))equalToWithRelation { MASMethodNotImplemented(); }
MSAViewConstraint
重写的方法,在其内部 做了条件判断,因为我们是单个约束,所以执行else代码块
- (MASConstraint * (^)(id, NSLayoutRelation))equalToWithRelation {
return ^id(id attribute, NSLayoutRelation relation) {
if ([attribute isKindOfClass:NSArray.class]) {
NSAssert(!self.hasLayoutRelation, @"Redefinition of constraint relation");
NSMutableArray *children = NSMutableArray.new;
for (id attr in attribute) {
MASViewConstraint *viewConstraint = [self copy];
viewConstraint.layoutRelation = relation;
viewConstraint.secondViewAttribute = attr;
[children addObject:viewConstraint];
}
MASCompositeConstraint *compositeConstraint = [[MASCompositeConstraint alloc] initWithChildren:children];
compositeConstraint.delegate = self.delegate;
[self.delegate constraint:self shouldBeReplacedWithConstraint:compositeConstraint];
return compositeConstraint;
} else {
NSAssert(!self.hasLayoutRelation || self.layoutRelation == relation && [attribute isKindOfClass:NSValue.class], @"Redefinition of constraint relation");
self.layoutRelation = relation;
self.secondViewAttribute = attribute;
return self;
}
};
}
在上面的代码中调用了self.secondViewAttribute = attribute;
, 会执行到下面的setter方法里。
make.left.equalTo(self.view).offset(100);
make.top.equalTo(self.view.mas_top).offset(100);
通过源码可知, 在日常写代码里 ,上面俩句是等价的,如果我们传进来一个view, 它就会用调用者的self.firstViewAttribute.layoutAttribute
来做初始化;
- (void)setSecondViewAttribute:(id)secondViewAttribute {
if ([secondViewAttribute isKindOfClass:NSValue.class]) {
[self setLayoutConstantWithValue:secondViewAttribute];
} else if ([secondViewAttribute isKindOfClass:MAS_VIEW.class]) {
_secondViewAttribute = [[MASViewAttribute alloc] initWithView:secondViewAttribute layoutAttribute:self.firstViewAttribute.layoutAttribute];
} else if ([secondViewAttribute isKindOfClass:MASViewAttribute.class]) {
_secondViewAttribute = secondViewAttribute;
} else {
NSAssert(NO, @"attempting to add unsupported attribute: %@", secondViewAttribute);
}
}
- 接着返回
MASViewConstraint
实例去调用offset
方法
返回Block,执行block;
- (MASConstraint * (^)(CGFloat))offset {
return ^id(CGFloat offset){
self.offset = offset;
return self;
};
}
- 最后所有的约束添加到工厂类的
constraints
数组中
执行工厂类的install
方法,
// MASConstraintMaker
- (NSArray *)install {
// 是否移除原有约束
if (self.removeExisting) {
// 获取当前view的所有约束
NSArray *installedConstraints = [MASViewConstraint installedConstraintsForView:self.view];
// 移除
for (MASConstraint *constraint in installedConstraints) {
[constraint uninstall];
}
}
// 记录的约束数组
NSArray *constraints = self.constraints.copy;
// 加载约束
for (MASConstraint *constraint in constraints) {
constraint.updateExisting = self.updateExisting;
[constraint install];
}
[self.constraints removeAllObjects];
return constraints;
}
- 再执行每一个
MASConstraint
约束对象的install
方法, 生成系统约束对象,加到对应的view上
- (void)install {
if (self.hasBeenInstalled) {
return;
}
if ([self supportsActiveProperty] && self.layoutConstraint) {
self.layoutConstraint.active = YES;
[self.firstViewAttribute.view.mas_installedConstraints addObject:self];
return;
}
MAS_VIEW *firstLayoutItem = self.firstViewAttribute.item;
NSLayoutAttribute firstLayoutAttribute = self.firstViewAttribute.layoutAttribute;
MAS_VIEW *secondLayoutItem = self.secondViewAttribute.item;
NSLayoutAttribute secondLayoutAttribute = self.secondViewAttribute.layoutAttribute;
// alignment attributes must have a secondViewAttribute
// therefore we assume that is refering to superview
// eg make.left.equalTo(@10)
if (!self.firstViewAttribute.isSizeAttribute && !self.secondViewAttribute) {
secondLayoutItem = self.firstViewAttribute.view.superview;
secondLayoutAttribute = firstLayoutAttribute;
}
MASLayoutConstraint *layoutConstraint
= [MASLayoutConstraint constraintWithItem:firstLayoutItem
attribute:firstLayoutAttribute
relatedBy:self.layoutRelation
toItem:secondLayoutItem
attribute:secondLayoutAttribute
multiplier:self.layoutMultiplier
constant:self.layoutConstant];
layoutConstraint.priority = self.layoutPriority;
layoutConstraint.mas_key = self.mas_key;
if (self.secondViewAttribute.view) {
MAS_VIEW *closestCommonSuperview = [self.firstViewAttribute.view mas_closestCommonSuperview:self.secondViewAttribute.view];
NSAssert(closestCommonSuperview,
@"couldn't find a common superview for %@ and %@",
self.firstViewAttribute.view, self.secondViewAttribute.view);
self.installedView = closestCommonSuperview;
} else if (self.firstViewAttribute.isSizeAttribute) {
self.installedView = self.firstViewAttribute.view;
} else {
self.installedView = self.firstViewAttribute.view.superview;
}
MASLayoutConstraint *existingConstraint = nil;
if (self.updateExisting) {
existingConstraint = [self layoutConstraintSimilarTo:layoutConstraint];
}
if (existingConstraint) {
// just update the constant
existingConstraint.constant = layoutConstraint.constant;
self.layoutConstraint = existingConstraint;
} else {
[self.installedView addConstraint:layoutConstraint];
self.layoutConstraint = layoutConstraint;
[firstLayoutItem.mas_installedConstraints addObject:self];
}
}
最后调用 install 装载约束,到此为止约束就被添加到view上了。
提示💡
之前只知道Masonry是使用的点链式语法,当然还有中括号链式语法。
链式语法参考链接
总结
-
NS_NOESCAPE
第一次遇到这个修饰符, 用于修饰block; - Masonry用到了
factory Method
设计模式,点链式语法
深受广大程序猿的喜欢;`