- (void)layoutSubviews
The default implementation of this method does nothing on iOS 5.1 and earlier. Otherwise, the default implementation uses any constraints you have set to determine the size and position of any subviews.
Subclasses can override this method as needed to perform more precise layout of their subviews. You should override this method only if the autoresizing and constraint-based behaviors of the subviews do not offer the behavior you want. You can use your implementation to set the frame rectangles of your subviews directly.
You should not call this method directly. If you want to force a layout update, call the setNeedsLayout method instead to do so prior to the next drawing update. If you want to update the layout of your views immediately, call the layoutIfNeeded method.
在iOS5.1之前,layoutSubviews默认的实现是什么都不做。但是,默认的实现使用你之前设置的约束来决定subviews的位置和大小。
子类可以重写此方法来更精确地去布局子视图。只有当autoresizing和 constraint-based行为去布局子视图的结果不能达到预期结果时,你才应该去重写此方法。你可以在自己的实现里,直接去设置subviews的frame。
不能直接调用layoutSubviews方法。如果你需要强制一个布局更新,调用setNeedsLayout方法,将会在下一个更新周期里调用layoutSubviews来更新子视图。如果想立即变更布局,调用layoutIfNeeded。
setNeedsLayout
- 标记布局需要更新
- 调用立即返回
- 在下一个更新周期更新布局
- 一定会调用layoutSubviews
layoutIfNeeded
- 立即更新布局
- 不一定会调用layoutSubviews方法。仅当发现布局有变更的时候调用。
使用总结
希望layoutSubviews一定调用,首先调用setNeedsLayout将视图标记为需要重新布局,如果想立即生效,接着调用layoutIfNeeded
func updateLayoutNow() {
self.view.setNeedsLayout()
self.view.layoutIfNeeded()
}
网友评论