-->

CAShapeLayer custom property is nil when drawInCon

2019-07-25 00:16发布

问题:

I denfined a custom layer,and declare a custom property,but it's not work when animation in -(void)drawInContext:(CGContextRef)ctx method

here is some code:

@interface ZBBProgressLayer : CAShapeLayer

@property (nonatomic, assign) CGFloat progress;
@property(nullable) CGColorRef progressColor;

@end

@implementation ZBBProgressLayer

+ (BOOL)needsDisplayForKey:(NSString *)key{
if ([key isEqualToString:@"progress"]/*progress 属性变化时,重绘*/) {
    return YES;
}
return [super needsDisplayForKey:key];
}

-(void)dealloc{
    [self removeAllAnimations];
}

@end

// ZBBRectProgressLayer
@interface ZBBRectProgressLayer : ZBBProgressLayer

@end

@implementation ZBBRectProgressLayer

-(void)drawInContext:(CGContextRef)ctx{

CGSize boundsSize = self.bounds.size;
CGFloat width = boundsSize.width * self.progress;

UIBezierPath *cutoutPath =[UIBezierPath bezierPathWithRect:CGRectMake(0,
                                                                      0,
                                                                      width,
                                                                          boundsSize.height)];


    CGContextSetFillColorWithColor(ctx,self.progressColor);
    CGContextAddPath(ctx, cutoutPath.CGPath);
    CGContextFillPath(ctx);
//    NSLog(@"%@ = %@\n",[self class],self);
}

@end

I use the layer like this:

-(void)setProgress:(CGFloat)progress animated:(BOOL)animated{

_progress = MIN(progress, 1);
if (animated) {
    CABasicAnimation* animation = [CABasicAnimation animationWithKeyPath:@"progress"];

    animation.duration = kAnimationDurationTime;
    animation.fromValue = @(_maskLayer.progress);
    animation.toValue = @(_progress);

    [_maskLayer addAnimation:animation forKey:@"progress"];
    _maskLayer.progress = _progress;
}else{
    _maskLayer.progress = _progress;
    [_maskLayer performSelectorOnMainThread:@selector(setNeedsDisplay) withObject:nil waitUntilDone:YES];
}
}

but animated == true,custom layer.progressColor is nil, animated == false,custom layer.progressColor is right.

source code : https://github.com/zhangbinbin5335/ZBBProgressView.git