欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

iOS 视图抖动

程序员文章站 2024-03-25 23:59:40
...

.h

/**
 添加抖动动画
 
 @param view 添加的视图
 */
+ (void)addAnimationShakeWithView:(UIView *)view;

/**
 移除抖动动画

 @param view 移除的视图
 */
+ (void)removeAnimationShakeWithView:(UIView *)view;

.m

#define kShakingRadian(R) ((R) / 180.0 * M_PI)

@implementation SHAnimation

#pragma mark - 添加抖动动画
+ (void)addAnimationShakeWithView:(UIView *)view{
    
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animation];
    
    animation.keyPath = @"transform.rotation";
    
    animation.values = @[@(kShakingRadian(-5)),  @(kShakingRadian(5)), @(kShakingRadian(-5))];
    
    animation.duration = 0.25;
    
    // 动画的重复执行次数
    animation.repeatCount = MAXFLOAT;
    
    // 保持动画执行完毕后的状态
    animation.removedOnCompletion = NO;
    
    animation.fillMode = kCAFillModeForwards;
    
    [view.layer addAnimation:animation forKey:@"sh_animation_shake"];
}

#pragma mark - 移除抖动动画
+ (void)removeAnimationShakeWithView:(UIView *)view{
    
    //结束动画
    [view.layer removeAnimationForKey:@"sh_animation_shake"];
}