layoutSubViews的使用

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.


最后一段说,不要直接调用此方法。如果你想强制更新布局,你可以调用setNeedsLayout方法;如果你想立即数显你的views,你需要调用layoutIfNeeded方法。

layoutSubviews作用

layoutSubviews是对subviews重新布局。比如,我们想更新子视图的位置的时候,可以通过调用layoutSubviews方法,既可以实现对子视图重新布局。
layoutSubviews默认是不做任何事情的,用到的时候,需要在自雷进行重写。

layoutSubviews以下情况会被调用

苹果官方文档已经强调,不能直接调用layoutSubviews对子视图进行重新布局。那么,layoutSubviews什么情况下会被调用呢?
以下几种情况layoutSubviews会被调用。
直接调用setLayoutSubviews(这个在上面苹果官方文档里有说明)
addSubview的时候。
viewframe发生改变的时候。
滑动UIScrollView的时候。
旋转Screen会触发父UIView上的layoutSubviews事件。
改变一个UIView大小的时候也会触发父UIView上的layoutSubviews事件。

注意:

viewframe的值为0的时候,addSubview也不会调用layoutSubviews的。
layoutSubviews方法在对子视图进行布局的时候非常方便。

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

推荐阅读更多精彩内容

  • ViewsBecause view objects are the main way your applicati...
    梁光飞阅读 3,856评论 0 0
  • 即使梦总会有醒的那一刻,我也希翼我们都可以是归来仍是少年的朗朗模样。走过的路路边的风景依旧是最初的心动,我们最是好...
    阿俊xi阅读 1,189评论 0 0
  • 周冲好样的! 自从无意间发现了周冲的影像声色公众号,每天都要看周冲更新的文章,有时还要把以前看过的文章重新看反复看...
    清风如水阅读 1,605评论 0 0
  • 有人22岁就毕业了, Someone graduated at the age of 22, 但等了五年才找到稳定...
    韩和侨阅读 3,332评论 0 0
  • 听郭德纲相声时,他说到,他练字,有段时间特别喜欢这四个字“万象归春”,当时这个包袱是由他徒弟岳云鹏来抖的,...
    我叫楊大山阅读 13,609评论 0 1