setNeedsLayout, layoutIfNeeded and layoutSubviews?之间的关系

setNeedsLayout is an easy one: it just sets a flag somewhere in the UIView that marks it as needing layout. That will force layoutSubviews 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 autoresizesSubviews 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.
setNeedsLayout:就是给个flag(标记着UIView需要layout的标志),UIView将会强制调用layoutSubviews,在下一次redraw发生前刷新。即异步调用layoutIfNeeded刷新布局,不立即刷新,在下一轮runloop结束前刷新,对于这一轮runloop之内的所有布局和UI上的更新只会刷新一次。
一般不需要手动调用,因为autoresizesSubviews这个属性,如果View的frame发生变化会调用layoutSubviews;
layoutSubView一般用来重写布局
layoutSubviews is the method in which you do all the interesting stuff. It's the equivalent of drawRect for layout, if you will. A trivial example might be:
-(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.
}

layoutIfNeeded 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 right now. Apple's implementation might look something like this:
layouIfNeeded一般会立刻对view做一个布局,看有没有刷新标记(setNeedLayout), 有这个标记则会调用layoutSubViews
-(void)layoutIfNeeded {
if (self._needsLayout) {
UIView *sv = self.superview;
if (sv._needsLayout) {
[sv layoutIfNeeded];
} else {
[self layoutSubviews];
}
}
}

你可能感兴趣的:(setNeedsLayout, layoutIfNeeded and layoutSubviews?之间的关系)