正文
关于
setNeedsLayout
,官方文档描述如下:
Call this method on your application’s main thread when you want to adjust the layout of a view’s subviews. This method makes a note of the request and returns immediately. Because this method does not force an immediate update, but instead waits for the next update cycle, you can use it to invalidate the layout of multiple views before any of those views are updated. This behavior allows you to consolidate all of your layout updates to one update cycle, which is usually better for performance.
(2)、layoutIfNeeded
用于更新视图以及其子视图布局,立即更新,不会等待更新周期,从根视图开始更新视图子树,若无待更新的布局,直接退出。
关于
layoutIfNeeded
,官方文档描述如下:
Use this method to force the view to update its layout immediately. When using Auto Layout, the layout engine updates the position of views as needed to satisfy changes in constraints. Using the view that receives the message as the root view, this method lays out the view subtree starting at the root. If no layout updates are pending, this method exits without modifying the layout or calling any layout-related callbacks.
(3)、layoutSubviews
一般是在
autoresizing
或者
constraint-based
的情况下重写此方法。常用场景是当视图不是使用frame初始化的时候,我们可以在此方法进行一些精细化布局。如子视图相对于父视图使用约束布局,子视图init时,不具有frame直到约束建立,因为不知道约束建立完成时机,而我们又确实需要frame进行一些计算,为确保计算时拿到的frame不为空,此时,我们可以将计算的过程放于此,并配合
setNeedsLayout
或者
layoutIfNeeded
进行视图刷新。