主要討論一下自定義view中layoutSubviews
的調用時機以及布局的一些tips.
先看官方文檔
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.
翻譯:
子類可以根據需要重寫此方法妻味,以便對其子視圖執(zhí)行更精確的布局伪煤。僅當子視圖的自動調整大小和基于約束的行為無法提供所需的行為時狮辽,才應重寫此方法⌒汲瑁可以使用實現直接設置子視圖的框矩形虏冻。
不應直接調用此方法渔肩。如果要強制更新布局逼友,請在下一次圖形更新之前調用setNeedsLayout()方法。如果要立即更新視圖的布局化借,請調用layoutIfNeeded()方法潜慎。
-
時機1
當自定義view 被添加到父view時
image.png -
時機2
當自定義view的size發(fā)生改變時,注意僅當Origin改變時不會執(zhí)行
image.png -
時機3
當自定義view自身添加子控件時
image.png -
時機4
當自定義view上面的子控件size反生改變時
image.png 時機5
當屏幕旋轉時會調用tips
當自身view認為需要重新布局時 都會調用layoutSubviews蓖康,而且我們能拿到view的frame铐炫,我們就可以動態(tài)的進行布局的計算,這也是一種適配的策略蒜焊,在layoutSubviews中我們可以重新設置子控件的布局驳遵,但是不應該把子控件的初始化放在里面,可以在init的時候對控件進行懶加載山涡,然后在layoutSubViews里面設置frame,當你使用約束進行布局時唆迁,可以不使用layoutSubviews這個方法鸭丛,直接在addsubview之后添加約束即可。
不足之處 歡迎補充