I have a class which is a subclass of UIView. I am able to draw stuff inside the view either by implementing the drawRect method, or by implementing drawLayer:inContext: which is a delegate method of CALayer.
I have two questions:
- How to decide which approach to use? Is there a use case for each one?
-
If I implement
drawLayer:inContext:, it is called (anddrawRectisn’t, at least as far as putting a breakpoint can tell), even if I don’t assign my view as theCALayerdelegate by using:[[self layer] setDelegate:self];how come the delegate method is called if my instance is not defined to be the layer’s delegate? and what mechanism prevents
drawRectfrom being called ifdrawLayer:inContext:is called?
Always use
drawRect:, and never use aUIViewas the drawing delegate for anyCALayer.Every
UIViewinstance is the drawing delegate for its backingCALayer. That’s why[[self layer] setDelegate:self];seemed to do nothing. It’s redundant. ThedrawRect:method is effectively the drawing delegate method for the view’s layer. Internally,UIViewimplementsdrawLayer:inContext:where it does some of its own stuff and then callsdrawRect:. You can see it in the debugger:This is why
drawRect:was never called when you implementeddrawLayer:inContext:. It’s also why you should never implement any of theCALayerdrawing delegate methods in a customUIViewsubclass. You should also never make any view the drawing delegate for another layer. That will cause all sorts of wackiness.If you are implementing
drawLayer:inContext:because you need to access theCGContextRef, you can get that from inside of yourdrawRect:by callingUIGraphicsGetCurrentContext().