Posted at

CoreAnimationのdelegate処理をblocks処理に置き換える

More than 5 years have passed since last update.


  1. CAAnimationのカテゴリとしてblocks定義。

  2. delegate処理する為にSingleton Class (ここではEEAnimationHandler)を作る。

  3. implement側のdelegate呼ばれるタイミングでblocks呼んであげる。


EEAnimationHandler.h

typedef void (^EEAnimationDidStopHandlerBlock)(CAAnimation *anim, BOOL finished);

typedef void (^EEAnimationDidStartHandlerBlock)(CAAnimation *anim);

@interface CAAnimation (handle)

@property (nonatomic, strong) EEAnimationDidStartHandlerBlock startHandlerBlock;
@property (nonatomic, strong) EEAnimationDidStopHandlerBlock stopHandlerBlock;
@property (nonatomic, strong) NSString *animationKey;
@property (nonatomic, weak) CALayer *addedLayer;

@end

@interface EEAnimationHandler : NSObject

+ (EEAnimationHandler *)sharedHandler;
- (void)registerAnimation:(CAAnimation *)animation toLayer:(CALayer *)layer forKey:(NSString *)key;

@end



EEAnimationHandler.m

@implementation EEAnimationHandler

- (void)registerAnimation:(CAAnimation *)animation toLayer:(CALayer *)layer forKey:(NSString *)aKey
{
animation.animationKey = key;
animation.addedLayer = layer;
animation.delegate = self;
[layer addAnimation:animation forKey:aKey];
}

#pragma mark - Animation Delegate
- (void)animationDidStart:(CAAnimation *)anim
{
if (anim.startHandlerBlock) anim.startHandlerBlock(anim);
}

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
if (anim.stopHandlerBlock) anim.stopHandlerBlock(anim, flag);
}


ざっくりはこんな感じ。

githubにアップしてますのでぜひ。