iOS开发在frame定位的时代,如果要想实现简单的移动动画,只需在下面这个方法的block里重写frame就可以实现
[UIViewanimateWithDuration:0.5 animations:^{
//在这重写frame
}];
而在autolayout的时代,我们没法重写frame,要想实现动画,我们可以重写约束,直接上代码
self.view5 = [[UIView alloc] init];
self.view5.backgroundColor = [UIColor greenColor];
[self.view addSubview:self.view5];
Bself(bself); //弱引用
//添加约束
[self.view5 mas_makeConstraints:^(MASConstraintMaker *make) {
//距顶上300
make.top.equalTo(bself.view).with.offset(300);
//水平居中
make.centerX.equalTo(bself.view);
//固定宽
make.width.mas_equalTo(@150);
//固定高
make.height.mas_equalTo(@60);
}];
//建个button
UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
button.backgroundColor = [UIColor blueColor];
[button addTarget:self action:@selector(clickedButton) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
[button mas_makeConstraints:^(MASConstraintMaker *make) {
make.top.equalTo(bself.view).with.offset(100);
make.centerX.equalTo(bself.view);
make.width.mas_equalTo(@100);
make.height.mas_equalTo(@50);
}];
//button点击方法
- (void)clickedButton
{
static BOOL isMove; //默认是NO
Bself(bself);
if (isMove) {
isMove = NO;
//添加动画
[UIView animateWithDuration:0.5 animations:^{
[bself.view5 mas_updateConstraints:^(MASConstraintMaker *make) {
//更改距顶上的高度
make.top.equalTo(bself.view).with.offset(300);
}];
//必须调用此方法,才能出动画效果(需要实现动画的view的父视图进行调用)
[bself.view layoutIfNeeded];
}];
}
else{
isMove = YES;
//开始动画
[UIView beginAnimations:nil context:nil];
//设定动画持续时间
[UIView setAnimationDuration:1];
[bself.view5 mas_updateConstraints:^(MASConstraintMaker *make) {
//动画的内容,更改距顶上的高度
make.top.equalTo(bself.view).with.offset(200);
}];
//必须调用此方法,才能出动画效果(需要实现动画的view的父视图进行调用)
[bself.view layoutIfNeeded];
//动画结束
[UIView commitAnimations];
}
}
这样就实现了每点击一次button,view5就上移100或下移100;就得一定要加上layoutIfNeeded方法刷新布局,不然无动画效果。还有bself是
#define WS(weakSelf) __weak __typeof(&*self)weakSelf = self;
这个其实没有必要,因为不会引起循环引用。