2011-08-11 43 views
7

我正在尝试制作一个“摇动”图标。UiImageView上的iPhone“颤抖”动画

上的装入我的控制器我创建这样一个计时器:

[NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(shakeIphonePic) userInfo:nil repeats:YES]; 

这是我的摇床方法:

- (void)shakeIphonePic 
{ 
    [UIView animateWithDuration:0.09 
          delay:0 
         options:UIViewAnimationOptionAllowUserInteraction 
        animations:^{ 
         self.iphonePic.layer.transform = CATransform3DMakeRotation(DegreesToRadians(8.0), 0.0, 0.0, 1.0); 
        } 
        completion:^(BOOL finished) { 
         [UIView animateWithDuration:0.09 
             animations:^(void) { 
              self.iphonePic.layer.transform = CATransform3DMakeRotation(DegreesToRadians(-16.0), 0.0, 0.0, 1.0); 
             }]; 
        } 
    ]; 
} 

它并不像我预想的那样好,但是......这不是主要问题。

看起来它显着减慢了我的用户界面的其余部分,这在以前是好的。

你可以建议我一个更有效的方式来摇动我的图标吗?

回答

27
CABasicAnimation* anim = [CABasicAnimation animationWithKeyPath:@"transform.rotation"]; 
[anim setToValue:[NSNumber numberWithFloat:0.0f]]; 
[anim setFromValue:[NSNumber numberWithDouble:M_PI/16]]; // rotation angle 
[anim setDuration:0.1]; 
[anim setRepeatCount:NSUIntegerMax]; 
[anim setAutoreverses:YES]; 
[self.viewYouAreShaking.layer addAnimation:anim forKey:@"iconShake"]; 

斯威夫特版本

let anim=CABasicAnimation(keyPath: "transform.rotation") 
anim.toValue=NSNumber(double: -M_PI/16) 
anim.fromValue=NSNumber(double: M_PI/16) 
anim.duration=0.1 
anim.repeatCount=1.5 
anim.autoreverses=true 
viewYouAreShaking.layer.addAnimation(anim, forKey: "iconShake") 
+1

一个很好的介绍是由马特·诺伊堡编程的iOS4的动画章。公共草案可在http://www.apeth.com/iOSBook/ch17.html – Jano

+0

如何关闭动画?我试过'[self.viewYouAreShaking.layer removeAllAnimations];'但是在你拿起手指后摇晃就停止了。我怎样才能让它忽略长时间接触并只识别长时间按下? – Mason