I have what I believe is equivalent code--for enabling implicit animation on a custom CALayer subclass property--behaving correctly in Objective-C and incorrectly in Swift.
@implementation CustomLayer
@dynamic thickness;
+(BOOL)needsDisplayForKey:(NSString*)key {
return [key isEqual: @"thickness"];
}
-(id<CAAction>)actionForKey:(NSString*)key {
NSLog(@"%@", key);
if([key isEqual:@"thickness"]) {
CABasicAnimation *anim = [[CABasicAnimation alloc] init];
anim.fromValue = [[self presentationLayer] valueForKey:key];
anim.duration = 2.0;
return anim;
} else {
return [super actionForKey:key];
}
}
-(void)drawInContext:(nonnull CGContextRef)ctx {
CGContextSetLineWidth(ctx, [self thickness]);
CGContextStrokeEllipseInRect(ctx, [self bounds]);
}
@end
// ...
[[self layer] setThickness:20.0]; // this triggers animation as expected
class CustomLayer : CALayer {
dynamic var thickness : CGFloat = 1.0
override func drawInContext(ctx: CGContext) {
CGContextSetLineWidth(ctx, thickness)
CGContextStrokeEllipseInRect(ctx, bounds)
}
override func actionForKey(event: String) -> CAAction? {
print(event)
if event == "thickness" {
let anim = CABasicAnimation()
anim.fromValue = presentationLayer()?.thickness
anim.duration = 2.0
return anim
} else {
return super.actionForKey(event)
}
}
class override func needsDisplayForKey(key:String) -> Bool {
if key == "thickness" {
return true
} else {
return super.needsDisplayForKey(key)
}
}
}
// ...
layer.thickness = 20.0 // nothing happens
Am I doing something wrong?