How to decide which approach to use? Is there a use case for each one?
Always use drawRect:
, and never use a UIView
as the drawing delegate for any CALayer
.
how come the delegate method is called if my instance is not defined to be the layer's delegate? and what mechanism prevents drawRect from being called if drawLayer:inContext:
is called?
Every UIView
instance is the drawing delegate for its backing CALayer
. That's why [[self layer] setDelegate:self];
seemed to do nothing. It's redundant. The drawRect:
method is effectively the drawing delegate method for the view's layer. Internally, UIView
implements drawLayer:inContext:
where it does some of its own stuff and then calls drawRect:
. You can see it in the debugger:
This is why drawRect:
was never called when you implemented drawLayer:inContext:
. It's also why you should never implement any of the CALayer
drawing delegate methods in a custom UIView
subclass. 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 the CGContextRef
, you can get that from inside of your drawRect:
by calling UIGraphicsGetCurrentContext()
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…