我有一个类,它是 UIView
的子类.我可以通过实现 drawRect
方法或通过实现 drawLayer:inContext:
这是 CALayer
.
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
.
我有两个问题:
如果我实现 drawLayer:inContext:
,它会被调用(而 drawRect
不是,至少就放置断点而言),即使我没有使用以下方法将我的视图分配为 CALayer
委托:
If I implement drawLayer:inContext:
, it is called (and drawRect
isn't, at least as far as putting a breakpoint can tell), even if I don't assign my view as the CALayer
delegate by using:
[[self layer] setDelegate:self];
如果我的实例未定义为层的委托,怎么会调用委托方法?如果 drawLayer:inContext:
被调用,什么机制会阻止 drawRect
被调用?
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?
如何决定使用哪种方法?每个都有用例吗?
How to decide which approach to use? Is there a use case for each one?
始终使用 drawRect:
,并且永远不要使用 UIView
作为任何 CALayer
的绘图委托.
Always use drawRect:
, and never use a UIView
as the drawing delegate for any CALayer
.
如果我的实例未定义为层的委托,怎么会调用委托方法?如果 drawLayer:inContext:
被调用,什么机制会阻止 drawRect 被调用?
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?
每个 UIView
实例都是其支持 CALayer
的绘图委托.这就是为什么 [[self layer] setDelegate:self];
似乎什么也没做.这是多余的.drawRect:
方法实际上是视图层的绘图委托方法.在内部,UIView
实现了 drawLayer:inContext:
,它自己做一些事情,然后调用 drawRect:
.你可以在调试器中看到:
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:
这就是为什么在您实现 drawLayer:inContext:
时从未调用过 drawRect:
.这也是为什么您永远不应该在自定义 UIView
子类中实现任何 CALayer
绘图委托方法的原因.您也不应该将任何视图作为另一层的绘图委托.这会导致各种古怪.
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.
如果您因为需要访问 CGContextRef
而实现 drawLayer:inContext:
,则可以从 drawRect:
内部获取它通过调用 UIGraphicsGetCurrentContext()
.
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()
.
这篇关于iOS:使用 UIView 的 'drawRect:' 与其层的委托 'drawLayer:inContext:'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!