きっと、もっと良い方法があるとは思うのですが、メモ的にブログに書きます。もっと良い実装があれば是非教えて欲しい!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];
地味に便利。
これまでアニメーションの一時停止ができなくてゲーム演出上困った局面に出くわしてましたが、これで切り抜けられそう。みんなも切り抜けてちょ。ではまた次回!















やりたいことはUIImageをtouchsBegan時にCGAffineTransformScaleでUIImageを拡大させtouchesEndedで一旦停止、次のtouchsBeganで拡大再開、〜繰り返し。
そのためにこちらの記事を参考にCALayerクラスを作り、touchesBeganメソッドの中に[self.layer pauseAnimation:NO]; 、touchesEndedメソッドの中に[self.layer pauseAnimation:YES]; をぶち込んだんですが、エラーを吐かれてしまいます。他にも試したのですがうまくいかない始末です。
こちらの方法で拡大アニメーションの一時停止・再開は可能なのでしょうか?もしよろしければヒントなど頂けないでしょうか?
いきなりの長い質問失礼しました。