Hi,
I can't find a decent answer to explain me the difference between these 2 functions. when does every one gets called, and how does one different then the other ?
for example , can't I just layout my views inside drawrect ?
Thanks
Hi,
I can't find a decent answer to explain me the difference between these 2 functions. when does every one gets called, and how does one different then the other ?
for example , can't I just layout my views inside drawrect ?
Thanks
Maybe I don't have all the answers, but I can say you that : - layoutSubviews is called when the view frame is changed - drawRect is called when setNeedDisplay is called
Most of the time you won't use layoutSubviews.
There may be others cases, but it could give you a first piece of answer ^^
Good luck
-layoutSubviews
is called from -layoutIfNeeded
if the "layout needed" flag was set (using -setNeedsLayout
, or automatically when the view bounds changes). Use it for positioning your view [EDIT: Use it for positioning subviews].
-drawRect:
is called from -displayIfNeeded
if the "display needed" flag was set (using -setNeedsDiplay
, or automatically if you set view.contentMode = UIViewContentModeRedraw
).
Both -layoutIfNeeded
and -displayIfNeeded
are called automatically by UIKit/CoreAnimation before things are drawn to screen; you rarely need to call them directly.
You can position your subviews in -drawRect:
(you can even add subviews!), but this is unwise:
-setNeedsDiplay
is not called automatically on a bounds change.-drawRect:
reduces performance (UIKit/CoreAnimation has to create a bitmap-backed graphics context for you); only do so if you need to perform custom drawing.-drawRect:
. Drawing is expensive. Moving views around is cheap.EDIT: And some more detail when I'm awake:
What's the difference between "display" and "draw"? Displaying is done by-[CALayer display]
; the default implementation is (approximately)
-displayLayer:
, call [self.delegate displayLayer:self]
. -displayLayer:
is supposed to set layer.content
to (e.g.) a CGImage,-drawLayer:inContext:
, set up a bitmap-backed context, call [self.delegate drawLayer:self inContext:context]
, and save the output to layer.content
(the output is actually a CABackingStore, which is presumably a private API)layer.content
.The view is the layer's delegate, so you can implement -[MyView displayLayer:]
instead, and do interesting stuff like
self.layer.contents = (id)([UIImage imageNamed:@"foo"].CGImage)
(which is roughly what UIImageView does)