Skip to content

Instantly share code, notes, and snippets.

@HHuckebein
Created February 1, 2014 17:31
Show Gist options
  • Save HHuckebein/8755567 to your computer and use it in GitHub Desktop.
Save HHuckebein/8755567 to your computer and use it in GitHub Desktop.
@interface CounterLayer : CALayer
@property (nonatomic, assign) NSInteger count;
@end
@interface MovingCounterView : UIView
@property (nonatomic, strong) CounterLayer *counterLayer;
@end
@implementation MovingCounterView
#pragma mark - CALayer Delegate
- (id)init
{
self = [super init];
if (self) {
[self.layer addSublayer:self.counterLayer];
}
return self;
}
- (CounterLayer *)counterLayer
{
if (nil == _counterLayer) {
CGRect frame = CGRectMake(0.f, 0.f, 25.f, 300.f);
_counterLayer = [CounterLayer layer];
_counterLayer.contentsScale = [[UIScreen mainScreen] scale];
_counterLayer.frame = frame;
// here we make sure we got informed
// when our layer animates
_counterLayer.delegate = self;
_counterLayer.contents = (id)[UIImage imageNamed:@"SomeImage"].CGImage;
}
return _counterLayer;
}
- (void)startMarkerAnimationToYPosition:(CGFloat)yPos duration:(CFTimeInterval)duration
{
CAMediaTimingFunction *timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
// position animation
CABasicAnimation *posAnim = [CABasicAnimation animationWithKeyPath:@"position"];;
posAnim.timingFunction = timingFunction;
// configure the posAnim as usual
[self.counterLayer addAnimation:posAnim forKey:@"position"];
// moving count animation
CABasicAnimation *countAnim = [CABasicAnimation animationWithKeyPath:@"count"];
countAnim.fromValue = @(0);
countAnim.toValue = @(200);
countAnim.duration = duration;
countAnim.timingFunction = timingFunction;
self.counterLayer.count = 200;
[self.counterLayer addAnimation:countAnim forKey:@"count"];
}
#pragma mark - CALayer Delegate
- (void)displayLayer:(CALayer *)layer
{
if ([layer isKindOfClass:[CounterLayer class]]) {
NSInteger currentCount = [[layer.presentationLayer valueForKey:@"count"] integerValue];
// update a text with this value
}
}
@end
@implementation CounterLayer
@dynamic count;
+ (BOOL)needsDisplayForKey:(NSString *)key
{
return [key isEqualToString:COUNT_KEY] || [super needsDisplayForKey:key];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment