iOS 为视图添加抖动效果

抖动效果在开发中比较少用到,不过有时使用了确有个很好的装逼效果,用的时候就例如一些用户错误操作之类的

效果如下,不过gif看到的效果没实际的好看

上代码

 1 - (void)shakeAnimationForView:(UIView *) view
 2 
 3 {
 4     // 获取到当前的View
 5     
 6     CALayer *viewLayer = view.layer;
 7     
 8     // 获取当前View的位置
 9     
10     CGPoint position = viewLayer.position;
11     
12     // 移动的两个终点位置
13     
14     CGPoint x = CGPointMake(position.x + 10, position.y);
15     
16     CGPoint y = CGPointMake(position.x - 10, position.y);
17     
18     // 设置动画
19     
20     CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position"];
21     
22     // 设置运动形式
23     
24     [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault]];
25     
26     // 设置开始位置
27     
28     [animation setFromValue:[NSValue valueWithCGPoint:x]];
29     
30     // 设置结束位置
31     
32     [animation setToValue:[NSValue valueWithCGPoint:y]];
33     
34     // 设置自动反转
35     
36     [animation setAutoreverses:YES];
37     
38     // 设置时间
39     
40     [animation setDuration:.06];
41     
42     // 设置次数
43     
44     [animation setRepeatCount:3];
45     
46     // 添加上动画
47     
48     [viewLayer addAnimation:animation forKey:nil];
49     
50     
51     
52 }

只要在需要的地方传进视图就可以了

例如:

 1     view1 = [[UIView alloc]initWithFrame:CGRectMake(50, 100, 50, 50)];
 2     view1.backgroundColor = [UIColor blueColor];
 3     view1.layer.cornerRadius = 25;
 4     [self.view addSubview:view1];
 5     
 6 }
 7 
 8 - (IBAction)beginView:(id)sender {
 9     [self shakeAnimationForView:view1];
10 }
原文地址:https://www.cnblogs.com/fcug/p/5197699.html