看到很多Autolayout寫的自定義控件中都實現了requiresConstraintBasedLayout
方法,一直不知道這個方法有什么用,因為不實現這個方法也沒發現有什么影響。經過查找資料,有解釋如下:
constraint-based layout engages lazily when someone tries to use it (e.g., adds a constraint to a view). If you do all of your constraint set up in -updateConstraints, you might never even receive updateConstraints if no one makes a constraint. To fix this chicken and egg problem, override this method to return YES if your view needs the window to use constraint-based layout.
意思就是基于約束的布局是懶觸發的,只有在添加了約束的情況下,系統才會自動調用updateConstraints
方法,如果把所有的約束放在 updateConstraints
中,那么系統將會不知道你的布局方式是基于約束的,所以重寫requiresConstraintBasedLayout
返回YES就是明確告訴系統:雖然我之前沒有添加約束,但我確實是基于約束的布局!這樣可以保證系統一定會調用 updateConstraints
方法 從而正確添加約束.