Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Make it possible to write Core Animation's animation code with blocks using timers.
@import QuartzCore;
@interface NSObject (CATransactionSupport)
- (NSTimer *)startTimerWithInterval:(NSTimeInterval)interval block:(void (^)(void))block;
- (void)startAnimationWithDuration:(NSTimeInterval)duration block:(void (^)(void))block;
- (void)startAnimationWithDuration:(NSTimeInterval)duration block:(void (^)(void))block completionHandler:(void (^)(void))completionHandler;
@end
@implementation NSObject (CATransactionSupport)
- (NSTimer *)startTimerWithInterval:(NSTimeInterval)interval block:(void (^)(void))block
{
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:interval
target:self
selector:@selector(__performBlockForTimer:)
userInfo:block
repeats:NO];
return timer;
}
- (void)__performBlockForTimer:(NSTimer *)timer
{
void (^block)(void) = timer.userInfo;
block();
}
- (void)startAnimationWithDuration:(NSTimeInterval)duration
block:(void (^)(void))block
{
[self startTimerWithInterval:0 block:^{
[CATransaction begin];
[CATransaction setAnimationDuration:duration];
block();
[CATransaction commit];
}];
}
- (void)startAnimationWithDuration:(NSTimeInterval)duration
block:(void (^)(void))block
completionHandler:(void (^)(void))completionHandler
{
[self startTimerWithInterval:0 block:^{
[CATransaction begin];
[CATransaction setAnimationDuration:duration];
[CATransaction setCompletionBlock:completionHandler];
block();
[CATransaction commit];
}];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment