現(xiàn)在iOS頁面布局用的最多的就是frame和Autolayout寞酿,實際上Autolayout的約束最終都是由系統(tǒng)轉(zhuǎn)換成frame來進行布局的。而當Autolayout與frame設(shè)置上產(chǎn)生沖突時椅挣,則會以Autolayout的設(shè)置為準。
跟布局相關(guān)的方法
- (void)setNeedsLayout;
- (void)layoutIfNeeded;
- (void)layoutSubviews;
setNeedsLayout方法標記當前view是需要重新布局的鸠天,在下一次runloop中烁涌,進行重新布局镀脂。如果想在當前的runloop中立刻更新布局,則通過調(diào)用layoutIfNeeded方法可以實現(xiàn)忘伞,此時系統(tǒng)會調(diào)用layoutSubviews薄翅,在layoutSubviews方法中,可以自己定義新的view或者改變子view的布局氓奈。
Autolayout相關(guān)的方法
//view的方法
- (void)updateConstraintsIfNeeded;
//重寫view中的方法
- (void)updateConstraints
- (BOOL)needsUpdateConstraints
- (void)setNeedsUpdateConstraints
//重寫viewController中的方法
- (void)updateViewConstraints
setNeedsUpdateConstraints只是標記當前view的約束需要在下一次runloop中更新翘魄,updateConstraintsIfNeeded如果過滿足更新條件會立刻調(diào)用updateConstraints來更新約束,updateConstraints是子view需要重寫的方法舀奶,來更新View的約束暑竟,最后需要調(diào)用[super updateConstraints],否則會崩育勺。而updateViewConstraints是定義在viewController中的但荤,方便去更新viewController對應(yīng)view的約束。
具體可以通過調(diào)用view的setNeedsUpdateConstraints來最終調(diào)用到viewController的updateViewConstraints方法來涧至,如果沒有這個方法腹躁,那么每次都要定義一個子view去重寫updateConstraints方法會比較繁瑣。updateConstraints和updateViewConstrains方法可以把約束的代碼和和業(yè)務(wù)邏輯分開南蓬,另外性能也更好纺非。
為什么會有setxxxxx和xxxifNeeded方法
setxxxxx方法可能是為了性能哑了,沒有在代碼更新布局或者約束之后立刻執(zhí)行,而是在下一次runloop中執(zhí)行烧颖。
xxxxIfNeeded方法則是為了在必要的時候弱左,立刻更新約束或者布局,舉個例子炕淮,有些時候同時使用動畫和autolayout拆火。