small medium large xlarge

05 Nov 2009, 03:54
Bill So (3 posts)

Hi Everyone,

I am trying to subclass CALayer and override drawInContext: method.

However, it never gets called in my sample app. I tried the CustomProperties sample code and it works. I don’t know why my code doesn’t. The only difference is… I am doing that in iPhone SDK.

Is it the drawInContext doesn’t work in iPhone?

I override drawInContext method this way:

  • (void)drawInContext:(CGContextRef)ctx { NSLog(@”called drawInContext”); [self drawNormalButtonInContext:ctx]; }

The console never prints the “called drawInContext” string.

I added my layer subclass in the awakeFromNib method of a UIView subclass

  • (void)awakeFromNib { KeyLayer *kLayer = [KeyLayer layerWithText:@”8”]; kLayer.position = CGPointMake(100.0, 100.0); [self.layer addSublayer:kLayer]; }

The UIView subclass has nth but just an empty drawRect method:

  • (void)drawRect:(CGRect)rect { // Drawing code }

Do you have any clues?

Thanks Bill

05 Nov 2009, 11:38
Bill Dudney (917 posts)

Hi Bill,

For drawInContext: method to get called you must call setNeedsDisplay on the layer.

Good luck!

05 Nov 2009, 13:20
Bill So (3 posts)

Hi Bill

Thank you very much for your hint.

Now I know why the documentation mentions “Subclassing CALayer and implementing one of the drawing methods does not automatically cause drawing to occur. You must explicitly cause the instance to re-cache the content, either by sending it a setNeedsDisplay or setNeedsDisplayInRect: message, or by setting its needsDisplayOnBoundsChange property to YES.”

Thanks loads! Bill

You must be logged in to comment