iOS開發之layoutSubviews的作用和調用機制
原文 http://www.superqq.com/blog/2015/07/27/ioskai-fa-zhi-layoutsubviewsde-zuo-yong-he-diao-yong-ji-zhi/
在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.
最后一段說,不要直接調用此方法。如果你想強制更新布局,你可以調用setNeedsLayout方法;如果你想立即數顯你的views,你需要調用layoutIfNeeded方法。
layoutSubviews作用
layoutSubviews是對subviews重新布局。比如,我們想更新子視圖的位置的時候,可以通過調用layoutSubviews方法,既可以實現對子視圖重新布局。
layoutSubviews默認是不做任何事情的,用到的時候,需要在自雷進行重寫。
layoutSubviews以下情況會被調用
蘋果官方文檔已經強調,不能直接調用layoutSubviews對子視圖進行重新布局。那么,layoutSubviews什么情況下會被調用呢?通過百度搜索,發現以下幾種情況layoutSubviews會被調用。
- 直接調用setLayoutSubviews。(這個在上面蘋果官方文檔里有說明)
- addSubview的時候。
- 當view的frame發生改變的時候。
- 滑動UIScrollView的時候。
- 旋轉Screen會觸發父UIView上的layoutSubviews事件。
- 改變一個UIView大小的時候也會觸發父UIView上的layoutSubviews事件。
我簡單測試了一下,上面基本都會被調用。 注意:
當view的fram的值為0的時候,`addSubview`也不會調用`layoutSubviews`的。
layoutSubviews方法在對自雷視圖進行布局的時候非常方便。可以自己動手,深入理解layoutSubviews的調用機制。
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!