Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I'm still trying to figure this out myself, so take this with some skepticism and forgive me if it contains errors.</p> <p><code>setNeedsLayout</code> is an easy one: it just sets a flag somewhere in the UIView that marks it as needing layout. That will force <code>layoutSubviews</code> to be called on the view before the next redraw happens. Note that in many cases you don't need to call this explicitly, because of the <code>autoresizesSubviews</code> property. If that's set (which it is by default) then any change to a view's frame will cause the view to lay out its subviews.</p> <p><code>layoutSubviews</code> is the method in which you do all the interesting stuff. It's the equivalent of <code>drawRect</code> for layout, if you will. A trivial example might be:</p> <pre><code>-(void)layoutSubviews { // Child's frame is always equal to our bounds inset by 8px self.subview1.frame = CGRectInset(self.bounds, 8.0, 8.0); // It seems likely that this is incorrect: // [self.subview1 layoutSubviews]; // ... and this is correct: [self.subview1 setNeedsLayout]; // but I don't claim to know definitively. } </code></pre> <p>AFAIK <code>layoutIfNeeded</code> isn't generally meant to be overridden in your subclass. It's a method that you're meant to call when you want a view to be laid out <em>right now</em>. Apple's implementation might look something like this:</p> <pre><code>-(void)layoutIfNeeded { if (self._needsLayout) { UIView *sv = self.superview; if (sv._needsLayout) { [sv layoutIfNeeded]; } else { [self layoutSubviews]; } } } </code></pre> <p>You would call <code>layoutIfNeeded</code> on a view to force it (and its superviews as necessary) to be laid out immediately.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload