core-animation-logo-sm-1きっと、もっと良い方法があるとは思うのですが、メモ的にブログに書きます。もっと良い実装があれば是非教えて欲しい!

UIViewのアニメーション、多くの人がこんな感じに実装していると思います。

[UIView beginAnimations:nil context:UIGraphicsGetCurrentContext()];
[UIView setAnimationCurve:UIViewAnimationCurveEaseOut];
[UIView setAnimationDuration:0.5];

// ここでアニメーションさせる内容を書く

[UIView commitAnimations];

ですが、ドキュメントをパッと見、アニメーションの一時停止/再開させるメソッドが見つからない。これは困ったぞ…という事でアレコレ探す事数カ月。ようやく一時停止/再開する実装のヒントをネットで見つけました。

How to pause the animation of a layer tree

なんと、CALayerを使います。まずは以下のソースをプロジェクトに追加。Objective-Cのカテゴリ機能で、CALayerにメソッドを1つ追加します。プロジェクトにQuartzCore.frameworkを追加するのも忘れずに。

nnCALayer.h
#import <QuartzCore/CALayer.h>

@interface CALayer (nnCALayer)

-(void)pauseAnimation:(BOOL)aPause;

@end

nnCALayer.m
#import "nnCALayer.h"

@implementation CALayer (nnCALayer)

-(void)pauseAnimation:(BOOL)aPause
{
    if(aPause)
    {
        CFTimeInterval pausedTime = [self convertTime:CACurrentMediaTime() fromLayer:nil];
        self.speed = 0.0;
        self.timeOffset = pausedTime;
    }
    else
    {
        CFTimeInterval pausedTime = [self timeOffset];
        self.speed = 1.0;
        self.timeOffset = 0.0;
        self.beginTime = 0.0;
        CFTimeInterval timeSincePause = [self convertTime:CACurrentMediaTime() fromLayer:nil] - pausedTime;
        self.beginTime = timeSincePause;
    }
}

@end

そしたら、UIView からこんな感じで呼び出してやる。
BOOL pause;     // YES:一時停止 / NO:再開
[self.layer pauseAnimation:pause];

地味に便利。

これまでアニメーションの一時停止ができなくてゲーム演出上困った局面に出くわしてましたが、これで切り抜けられそう。みんなも切り抜けてちょ。ではまた次回!