現(xiàn)在iOS頁面布局用的最多的就是frame和Autolayout,實(shí)際上Autolayout的約束最終都是由系統(tǒng)轉(zhuǎn)換成frame來進(jìn)行布局的。而當(dāng)Autolayout與frame設(shè)置上產(chǎn)生沖突時(shí),則會(huì)以Autolayout的設(shè)置為準(zhǔn)。
跟布局相關(guān)的方法
- (void)setNeedsLayout;
- (void)layoutIfNeeded;
- (void)layoutSubviews;
setNeedsLayout方法標(biāo)記當(dāng)前view是需要重新布局的,在下一次runloop中,進(jìn)行重新布局。如果想在當(dāng)前的runloop中立刻更新布局,則通過調(diào)用layoutIfNeeded方法可以實(shí)現(xiàn),此時(shí)系統(tǒng)會(huì)調(diào)用layoutSubviews,在layoutSubviews方法中,可以自己定義新的view或者改變子view的布局。
Autolayout相關(guān)的方法
//view的方法
- (void)updateConstraintsIfNeeded;
//重寫view中的方法
- (void)updateConstraints
- (BOOL)needsUpdateConstraints
- (void)setNeedsUpdateConstraints
//重寫viewController中的方法
- (void)updateViewConstraints
setNeedsUpdateConstraints只是標(biāo)記當(dāng)前view的約束需要在下一次runloop中更新,updateConstraintsIfNeeded如果過滿足更新條件會(huì)立刻調(diào)用updateConstraints來更新約束,updateConstraints是子view需要重寫的方法,來更新View的約束,最后需要調(diào)用[super updateConstraints],否則會(huì)崩。而updateViewConstraints是定義在viewController中的,方便去更新viewController對(duì)應(yīng)view的約束。
具體可以通過調(diào)用view的setNeedsUpdateConstraints來最終調(diào)用到viewController的updateViewConstraints方法來,如果沒有這個(gè)方法,那么每次都要定義一個(gè)子view去重寫updateConstraints方法會(huì)比較繁瑣。updateConstraints和updateViewConstrains方法可以把約束的代碼和和業(yè)務(wù)邏輯分開,另外性能也更好。
為什么會(huì)有setxxxxx和xxxifNeeded方法
setxxxxx方法可能是為了性能,沒有在代碼更新布局或者約束之后立刻執(zhí)行,而是在下一次runloop中執(zhí)行。
xxxxIfNeeded方法則是為了在必要的時(shí)候,立刻更新約束或者布局,舉個(gè)例子,有些時(shí)候同時(shí)使用動(dòng)畫和autolayout。