iOS长按图片触发CABasicAnimation晃动动画

//长按图片触发CABasicAnimation晃动动画; 点击任意位置停止动画。

#import “ViewController.h”

@interface ViewController ()<UIGestureRecognizerDelegate>

@property (weak, nonatomic) IBOutlet UIImageView *shakeImageView;

@end

@implementation ViewController

– (void)viewDidLoad {

    [super viewDidLoad];

    //开始写代码,给_shakeImageView添加长按手势

    UILongPressGestureRecognizer * longPressGr = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressToDo:)];

    longPressGr.delegate = self;

    [_shakeImageView setUserInteractionEnabled:YES];

    [_shakeImageView addGestureRecognizer:longPressGr];

}

//开始写代码,使用CABasicAnimation使图片长按时无限左右晃动

-(void)longPressToDo:(UILongPressGestureRecognizer *)gesture {

    CABasicAnimation *shake = [CABasicAnimation animationWithKeyPath:@”transform.translation.x”];

    shake.duration = 1;

    shake.autoreverses = YES;

    shake.repeatCount = MAXFLOAT;

    shake.delegate = self;

    shake.fromValue = [NSNumber numberWithFloat:-50];

    shake.toValue = [NSNumber numberWithFloat:50];

    [[_shakeImageView layer] addAnimation:shake forKey:@”shareAnimation”];

}

//开始写代码,点击任意位置取消晃动动画

– (void)touchesBegan:(UITouch *)touches withEvent:(UIEvent *)event

{

    [_shakeImageView.layer removeAllAnimations];

}

@end

分享到: 更多
Separator image Posted in IOS.