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
-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 -setNeedsDisplay
, 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:
-setNeedsDisplay
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)If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With