今天在学习masonry框架的时候,看到第二个demo,Update View.
其中有个方法是:+ (BOOL)requiresConstraintBasedLayout.
这个方法的意思是: 如果你在- (void)updateConstraints这个方法里面给自定义的控件更新控件的constraint,那么需要重写+ (BOOL)requiresConstraintBasedLayout方法,并且返回YES.否则的话,就不会显示该控件.
如果直接在init方法中设置自定义控件的constraint,那么则不需要重写+ (BOOL)requiresConstraintBasedLayout方法,也可以显示
例如:下面的这个代码,我将自动布局写到- (void)updateConstraints这个方法中了,所以我需要重写+ (BOOL)requiresConstraintBasedLayout这个方法,否则的话就不会显示出来自定义的控件.
而且,我在下面的每个方法中都定义了输出NSLog();这样我们可以看出来程序在执行的时候一个先后顺序:
#import "SLExampleUpdateView.h"
@interface SLExampleUpdateView ()
@property (nonatomic, strong)UIButton * growingButton;
@property (nonatomic, assign) CGSize buttonSize;
@property (nonatomic, strong) UIView * redView;
@end
@implementation SLExampleUpdateView
- (instancetype)init{
NSLog(@"init");
self = [super init];
if (!self) return nil;
UIView * superview = self;
self.redView = [[UIView alloc] init];
self.redView.backgroundColor = UIColor.redColor;
self.redView.layer.borderColor = UIColor.blackColor.CGColor;
self.redView.layer.borderWidth = 2;
[self addSubview:self.redView];
return self;
}
- (void)updateConstraints {
NSLog(@"updateConstrains");
[self.redView makeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(self).offset(10);
make.left.equalTo(self).offset(10);
make.bottom.equalTo(self).offset(-10);
make.right.equalTo(self).offset(-10);
}];
[super updateConstraints];
}
+ (BOOL)requiresConstraintBasedLayout {
NSLog(@"requires");
return YES;
}
- (void)layoutSubviews {
[super layoutSubviews];
NSLog(@"layoutSubviews");
}
@end