在UIView里面有一個方法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.
官方文檔解釋
我們先來看看蘋果官方文檔的解釋:
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.
最后一段說,不要直接調(diào)用此方法诡挂。如果你想強(qiáng)制更新布局瞻离,你可以調(diào)用setNeedsLayout方法腾仅;如果你想立即數(shù)顯你的views,你需要調(diào)用layoutIfNeeded方法套利。
layoutSubviews作用
layoutSubviews是對subviews重新布局推励。比如,我們想更新子視圖的位置的時候肉迫,可以通過調(diào)用layoutSubviews方法验辞,既可以實現(xiàn)對子視圖重新布局。
layoutSubviews默認(rèn)是不做任何事情的喊衫,用到的時候跌造,需要在自類進(jìn)行重寫。
layoutSubviews以下情況會被調(diào)用
蘋果官方文檔已經(jīng)強(qiáng)調(diào),不能直接調(diào)用layoutSubviews對子視圖進(jìn)行重新布局壳贪。那么陵珍,layoutSubviews什么情況下會被調(diào)用呢?通過百度搜索违施,發(fā)現(xiàn)以下幾種情況layoutSubviews會被調(diào)用互纯。
1、直接調(diào)用setLayoutSubviews磕蒲。(這個在上面蘋果官方文檔里有說明)
2留潦、addSubview的時候。
3辣往、當(dāng)view的frame發(fā)生改變的時候兔院。
4、滑動UIScrollView的時候排吴。
5秆乳、旋轉(zhuǎn)Screen會觸發(fā)父UIView上的layoutSubviews事件懦鼠。
6、改變一個UIView大小的時候也會觸發(fā)父UIView上的layoutSubviews事件。
注意:
1叔扼、當(dāng)view的fram的值為0的時候突诬,
addSubview
也不會調(diào)用layoutSubviews
的。
2睦袖、init初始化不會觸發(fā)layoutSubviews
layoutSubviews方法在對自類視圖進(jìn)行布局的時候非常方便珊肃。
參考:
http://www.open-open.com/lib/view/open1438053045972.html