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...
    梁光飛閱讀 641評論 0 0
  • 即使夢總會有醒的那一刻,我也希翼我們都可以是歸來仍是少年的朗朗模樣。走過的路路邊的風景依舊是最初的心動,我們最是好...
    阿俊xi閱讀 178評論 0 0
  • 周沖好樣的! 自從無意間發現了周沖的影像聲色公眾號,每天都要看周沖更新的文章,有時還要把以前看過的文章重新看反復看...
    清風如水閱讀 239評論 0 0
  • 有人22歲就畢業了, Someone graduated at the age of 22, 但等了五年才找到穩定...
    韓和僑閱讀 486評論 0 0
  • 聽郭德綱相聲時,他說到,他練字,有段時間特別喜歡這四個字“萬象歸春”,當時這個包袱是由他徒弟岳云鵬來抖的,...
    我叫楊大山閱讀 10,636評論 0 1