I’m struggling to find the missing piece in my code.I have a class which derives from UIView(customView) and also have a class that derives from CALayer (customLayer) and implements the drawLayer:inContext delegate method of the CALayer class.I do that because I want to use the customLayer as a clipping mask and so I need the drawLayer: inContext method which is not called when I start the application.
Here is a snippet of my code
@implementation CustomView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
self.backgroundColor = [UIColor lightGrayColor];
// Initialization code
CustomLayer *customLayer= [CALayer layer];
customLayer.backgroundColor= [UIColor colorWithRed:0 green:0.6 blue:0.2 alpha:0.4].CGColor;
customLayer.frame = self.bounds;
customLayer.delegate=customLayer;
[customLayer setNeedsDisplay];
[self.layer addSublayer:customLayer];
}
return self;
}
and the customLayer implementation:
@implementation CustomLayer
-(void) drawLayer:(CALayer *)layer inContext:(CGContextRef)ctx
{
NSLog(@"drawLayer:inContext");
CGContextBeginPath (ctx);
CGContextAddEllipseInRect(ctx, self.frame);
CGContextClosePath (ctx);
CGContextClip (ctx);
}
I really can’t figure out what is going on.Any advices will be greatly appreciated.
Updating based on conversation in comments
First, this line:
needs to use your CustomLayer:
That said, setting the customLayer as its own delegate is a bit odd, you may actually be running into code preventing this.
Have you tried using the
- (void)drawInContext:(CGContextRef)ctxmethod? Generally, each CALayerDelegate method has a corresponding CALayer method that you can override in subclasses.Also, are you setting the frame (bounds/position//center) of the CustomLayer instance? I see you adding it to the layer hierarchy, but at the default 0,0 size.