Help us understand the problem. What is going on with this article?

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

More than 3 years have passed since last update.

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 のホーム画面でのアイコン移動と同じような雰囲気のアプリを作れるよ。

magickworx
iOS App Developer, FreeBSD User
https://iphone.magickworx.com/
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした