UIView的几个重要方法

一、layoutSubViews

官方文档

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.

从文档中可以发现两点很重要的
  1. 应用场景为:当系统的子控件布局不满住需求的时候,重写该方法
  2. 不应该直接调用该方法
此外还需要知道触发的时机
  1. 被add到父视图中的时候(初始化不会触发)
  2. 被改变Size大小(改变位置不触发)
  3. UIScrollView控件滑动的时候
  4. 旋转设备

二、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.

从文档中可以看到两点比较重要
  1. 该方法不会立即更新,而是等到下一次的更新周期才会更新布局
  2. 这样的写法对性能有好处

三、layoutIfNeeded

官方文档

Use this method to force the layout of subviews before drawing. Using the view that receives the message as the root view, this method lays out the view subtree starting at the root.

从文档中可以发现
  1. 该方法可以强制刷新布局
  2. 该方法会从当前视图开始布局当前视图以及所有子视图

实际应用场景

...(后续更新)

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容