animateWithDurationメソッドはUIViewクラスに以前からあるアニメーションのクラスメソッドですが、usingSpringWithDampingパラメータがあるこのメソッドはiOS7.0で追加されています。
このメソッドを利用すると、usingSpringWithDampingのパラメータが示すようにスプリングのような値の変化を作ることができます。次に簡単な使用例を示します。ボタンをタップすると画面のランダムな場所にボタンが移動しますが、目的地点にスプリングのように着地します。
実装ファイルは次のとおりです。
//
// ViewController.m
// ex_animateWithDuration_usingSpringWithDamping
//
// Created by yoshiyuki oshige on 2014/02/22.
// Copyright (c) 2014年 yoshiyuki. All rights reserved.
//
#import "ViewController.h"
@interface ViewController ()
// ボタンをアウトレット接続してプロパティ宣言する
@property (weak, nonatomic) IBOutlet UIButton *myButton;
// ボタンをアクション接続してメソッド宣言する
- (IBAction)playAnimation:(UIButton *)sender;
// ランダムな点を作るメソッド
- (CGPoint) randomPoint;
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
// アニメーションの開始
- (IBAction)playAnimation:(UIButton *)sender {
[UIView animateWithDuration:1.0
delay:0.0
usingSpringWithDamping:0.3
initialSpringVelocity:0.5
options:UIViewAnimationOptionCurveLinear
animations:^{
self.myButton.center = [self randomPoint];
}
completion:nil];
}
// ランダムな点を返す
- (CGPoint) randomPoint
{
int w = self.view.frame.size.width;
int h = self.view.frame.size.height-30;
CGPoint pt = CGPointMake(arc4random()%w, arc4random()%h+20);
return pt;
}
@end