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的時候。
當view
的frame
發生改變的時候。
滑動UIScrollView
的時候。
旋轉Screen
會觸發父UIView
上的layoutSubviews
事件。
改變一個UIView
大小的時候也會觸發父UIView
上的layoutSubviews
事件。
注意:
當view
的frame
的值為0的時候,addSubview
也不會調用layoutSubviews
的。
layoutSubviews
方法在對子視圖進行布局的時候非常方便。