首先我们查看下layoutSubviews如何调用
- (void)layoutSubviews; // override point. called by layoutIfNeeded automatically. As of iOS 6.0, when constraints-based layout is used the base implementation applies the constraints-based layout, otherwise it does nothing.
简单的说就是你如果想调用此方法.不要直接调用,需要调用setNeedsLayout方法来刷新布局!
看看官方怎么说吧!
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.
我们直接看说重点(本人英文也是渣渣,就不翻译了,也不会翻译哈:-D):
不要直接调用layoutSubviews方法。如果你想强制更新布局,你可以调用setNeedsLayout方法;如果你想立即数显你的views,你需要调用layoutIfNeeded方法。
那么问题来了,那layoutSubviews有毛用呀!你这样想就得好好看看这篇文章了!
layoutSubviews的作用:
我们不是经常要对subviews布局么,更新啥的,layoutSubviews就是对subviews重新布局的,常常需要根据需求来更新对应的subview大小,这样才能显示完美,不会挨批了!
那么我们要在啥时候调用layoutSubviews,layoutSubviews什么时候会被调用呢?
layoutSubviews在以下情况下会被调用:
1、直接调用setLayoutSubviews,setNeedsLayout
2、init初始化不会触发layoutSubviews
3、addSubview会触发layoutSubviews
4、设置view的Frame会触发layoutSubviews,当然前提是frame的值设置前后发生了变化
5、滚动一个UIScrollView会触发layoutSubviews
6、旋转Screen会触发父UIView上的layoutSubviews事件
7、改变一个UIView大小的时候也会触发父UIView上的layoutSubviews事件
这样我们根据不同场景来触发layoutSubviews.
我们还得注意一些细节
当view的frame为zero的时候 addSubview不会触发layoutSubviews
最后:
layoutSubviews我理解的比较浅,希望大家可以指出文章的错误指出,也希望可以跟大家探讨如何更加深入 调用layoutSubviews的机制