LoginSignup
27
27

More than 5 years have passed since last update.

[iOS] UIView をプルプルさせる

Last updated at Posted at 2014-12-15

iOS デバイスのホーム画面でアイコンを長押しすると、アイコンがプルプルとふるえ出す。同じような効果を自作アプリでも実現するための汎用的なコード。UIView (サブクラスも)であれば、何でもプルプルできるよ。

static CGFloat
DegreesToRadians(CGFloat degrees) // XXX: マクロでも良いけど関数で実装
{
  return degrees * M_PI / 180.0f; // 度からラジアンに変換するだけ
}

static NSString * const kVibrateAnimationKey = @"VibrateAnimationKey";

-(void)vibrated:(BOOL)vibrated view:(UIView *)view
{
  if (vibrated) {
    CABasicAnimation * animation;
    animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
    animation.duration  = 0.25; // プルプル間隔(短いと早く、長いとゆっくり)
    animation.fromValue = @(DegreesToRadians(3.0f));  // プルプルの振れ幅(5.0fまでが無難)
    animation.toValue   = @(DegreesToRadians(-3.0f)); // プルプルの振れ幅(5.0fまでが無難)
    animation.repeatCount  = INFINITY;
    animation.autoreverses = YES;
    [view.layer addAnimation:animation forKey:kVibrateAnimationKey];
  }
  else {
    [view.layer removeAnimationForKey:kVibrateAnimationKey];
  }
}

仕組みは単純で、CALayer に回転アニメーションを無限に実行させているだけ。上記ソースコードのコメント付きの行の値を変更すれば、お好みのプルプル動作になると思う。

また、UIPanGestureRecognizer のドラッグ時に利用すれば、iOS のホーム画面でのアイコン移動と同じような雰囲気のアプリを作れるよ。

27
27
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
27
27