#import "MASExampleUpdateView.h"
@interface MASExampleUpdateView ()
@property (nonatomic, strong) UIButton *growingButton;
@property (nonatomic, assign) CGSize buttonSize;
@end
@implementation MASExampleUpdateView
- (id)init {
self = [super init];
if (!self) return nil;
self.growingButton = [UIButton buttonWithType:UIButtonTypeSystem];
[self.growingButton setTitle:@"Grow Me!" forState:UIControlStateNormal];
self.growingButton.layer.borderColor = UIColor.greenColor.CGColor;
self.growingButton.layer.borderWidth = 3;
[self.growingButton addTarget:self action:@selector(didTapGrowButton:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:self.growingButton];
self.buttonSize = CGSizeMake(100, 100);
return self;
}
//返回view是否是autoLayout布局模式,返回值决定了是否是autoLayout布局模式。使用autolayout返回YES
+ (BOOL)requiresConstraintBasedLayout
{
return YES;
}
// this is Apple's recommended place for adding/updating constraints
//系统更新约束 如果你的view需要在子view间创建约束,需要实现该方法
/**添加本地约束的地方是 updateConstraints。确保在你的实现中增加任何你需要布局子视图的约束条件之后,调用一下 [super updateConstraints]。
在这个方法中,你不会被允许禁用何约束条件,因为你已经进入上面所描述的布局过程的第一步了(参考 http://blog.csdn.net/jeffasd/article/details/50454588)。如果尝试着这样做,将会产生一个友好的错误信息 “programming error”。
如果稍后一个失效的约束条件发生了改变的话,你需要立刻移除这个约束并调用 setNeedsUpdateConstraints。事实上,仅在这种情况下你需要触发更新约束条件的操作。
*/
- (void)updateConstraints {
[self.growingButton updateConstraints:^(MASConstraintMaker *make) {
make.center.equalTo(self);
make.width.equalTo(@(self.buttonSize.width)).priorityLow();
make.height.equalTo(@(self.buttonSize.height)).priorityLow();
make.width.lessThanOrEqualTo(self);
make.height.lessThanOrEqualTo(self);
}];
//according to apple super should be called at end of method
[super updateConstraints];
}
- (void)didTapGrowButton:(UIButton *)button {
self.buttonSize = CGSizeMake(self.buttonSize.width * 1.3, self.buttonSize.height * 1.3);
// tell constraints they need updating
//如果稍后一个失效的约束条件发生了改变的话,你需要立刻移除这个约束并调用 setNeedsUpdateConstraints。
//事实上,仅在这种情况下你需要触发更新约束条件的操作。
[self setNeedsUpdateConstraints];
// update constraints now so we can animate the change
//告知立刻更新约束
[self updateConstraintsIfNeeded];
[UIView animateWithDuration:0.4 animations:^{
//告知页面布局立刻更新。所以一般都会和setNeedsLayout一起使用。
//如果希望立刻生成新的frame需要调用此方法,利用这点一般布局动画可以在更新布局后直接使用这个方法让动画生效。
[self layoutIfNeeded];
}];
}
@end