Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
26
Help us understand the problem. What is going on with this article?
@magickworx

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

26
Help us understand the problem. What is going on with this article?
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
magickworx
プログラマ。iOS アプリ開発者。FreeBSD 愛好者。個人事業主。

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
26
Help us understand the problem. What is going on with this article?