废话不多说,直接上代码:
首先在.h中声明如下参数:
float imageWidth;//图片宽度
UIImageView *moveView;
UIButton *button;
int touchNumber;//点击次数
在.m中创建视图:
self.view.backgroundColor = [UIColor whiteColor];
//创建imageview
UIImage *image = [UIImage imageNamed:@"photo.jpg"];
imageWidth = image.size.width;
moveView = [[UIImageView alloc] initWithFrame:CGRectMake(-imageWidth, 200, imageWidth, image.size.height)];
moveView.image = image;
moveView.backgroundColor = [UIColor redColor];
[self.view addSubview:moveView];
//创建按钮
button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(100, 100, 100, 30);
[button setTitle:@"Touch me" forState:UIControlStateNormal];
[button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
[button addTarget:self action:@selector(doSomething) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
touchNumber = 1;//默认为1;
按钮点击事件:
/*
*第一次点击按钮,图片从左侧平移过来
*touchNumber自加1
*再次点击,imageview只执行抖动动画
*/
- (void) doSomething
{
if (touchNumber == 1) {
//添加平移动画,
[UIView animateWithDuration:0.5 animations:^{
moveView.center = CGPointMake(moveView.center.x + imageWidth/2 + [UIScreen mainScreen].bounds.size.width/2, moveView.center.y);
} completion:^(BOOL finished) {
//平移结束添加抖动动画
[self shakeAnimation];
}];
}
else{
[self shakeAnimation];
}
++ touchNumber;
}
抖动动画:
- (void) shakeAnimation
{
CABasicAnimation* shake = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
//设置抖动幅度
shake.fromValue = [NSNumber numberWithFloat:+0.1];
shake.toValue = [NSNumber numberWithFloat:-0.1];
shake.duration = 0.1;
shake.autoreverses = YES; //是否重复
shake.repeatCount = 4;
[moveView.layer addAnimation:shake forKey:@"imageView"];
moveView.alpha = 1.0;
[UIView animateWithDuration:2.0
delay:2.0
options:UIViewAnimationOptionCurveEaseIn
animations:nil completion:nil];
}
动画效果: