看到很多Autolayout寫的自定義控件中都實(shí)現(xiàn)了requiresConstraintBasedLayout方法,一直不知道這個(gè)方法有什么用,因?yàn)椴粚?shí)現(xiàn)這個(gè)方法也沒發(fā)現(xiàn)有什么影響。經(jīng)過查找資料,有解釋如下:
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.
意思就是基于約束的布局是懶觸發(fā)的,只有在添加了約束的情況下,系統(tǒng)才會(huì)自動(dòng)調(diào)用updateConstraints方法,如果把所有的約束放在 updateConstraints中,那么系統(tǒng)將會(huì)不知道你的布局方式是基于約束的,所以重寫requiresConstraintBasedLayout 返回YES就是明確告訴系統(tǒng):雖然我之前沒有添加約束,但我確實(shí)是基于約束的布局!這樣可以保證系統(tǒng)一定會(huì)調(diào)用 updateConstraints 方法 從而正確添加約束.