iOS中AutoLayer自動布局流程及相關方法【轉】

來源:互聯網
上載者:User

標籤:

轉自:http://my.oschina.net/w11h22j33/blog/208574

關於UIView的Layer,IOS提供了三個方法:

1、layoutSubviews

在iOS5.1和之前的版本,此方法的預設實現不會做任何事情(實現為空白),iOS5.1之後(iOS6開始)的版本,此方法的預設實現是使用你設定在此view上面的constraints(Autolayout)去決定subviews的position和size。 UIView的子類如果需要對其subviews進行更精確的布局,則可以重寫此方法。只有在autoresizingconstraint-based behaviors of subviews不能提供我們想要的布局結果的時候,我們才應該重寫此方法。可以在此方法中直接設定subviews的frame。 我們不應該直接調用此方法,而應當用下面兩個方法。

2、setNeedsLayout

此方法會將view當前的layout設定為無效的,並在下一個upadte cycle裡去觸發layout更新。

3、layoutIfNeeded

使用此方法強制立即進行layout,從當前view開始,此方法會遍曆整個view層次(包括superviews)請求layout。因此,調用此方法會強制整個view層次布局。

 

基於約束的AutoLayer的方法:

1、setNeedsUpdateConstraints

當一個自訂view的某個屬性發生改變,並且可能影響到constraint時,需要調用此方法去標記constraints需要在未來的某個點更新,系統然後調用updateConstraints.

2、needsUpdateConstraints

constraint-based layout system使用此傳回值去決定是否需要調用updateConstraints作為正常版面配置階段的一部分。

3、updateConstraintsIfNeeded

立即觸發約束更新,自動更新布局。

4、updateConstraints

 

自訂view應該重寫此方法在其中建立constraints. 注意:要在實現在最後調用[super updateConstraints]

Auto Layout Process 自動版面配置階段

與使用springs and struts(autoresizingMask)比較,Auto layout在view顯示之前,多引入了兩個步驟:updating constraints 和laying out views。每一個步驟都依賴於上一個。display依賴layout,而layout依賴updating constraints。 updating constraints->layout->display

第一步:updating constraints,被稱為測量階段,其從下向上(from subview to super view),為下一步layout準備資訊。可以通過調用方法setNeedUpdateConstraints去觸發此步。constraints的改變也會自動的觸發此步。但是,當你自訂view的時候,如果一些改變可能會影響到布局的時候,通常需要自己去通知Auto layout,updateConstraintsIfNeeded。

自訂view的話,通常可以重寫updateConstraints方法,在其中可以添加view需要的局部的contraints。

第二步:layout,其從上向下(from super view to subview),此步主要應用上一步的資訊去設定view的center和bounds。可以通過調用setNeedsLayout去觸發此步驟,此方法不會立即應用layout。如果想要系統立即的更新layout,可以調用layoutIfNeeded。另外,自訂view可以重寫方法layoutSubViews來在layout的工程中得到更多的定製化效果。

第三步:display,此步時把view渲染到螢幕上,它與你是否使用Auto layout無關,其操作是從上向下(from super view to subview),通過調用setNeedsDisplay觸發,

因為每一步都依賴前一步,因此一個display可能會觸發layout,當有任何layout沒有被處理的時候,同理,layout可能會觸發updating constraints,當constraint system更新改變的時候。

需要注意的是,這三步不是單向的,constraint-based layout是一個迭代的過程,layout過程中,可能去改變constraints,有一次觸發updating constraints,進行一輪layout過程。

注意:如果你每一次調用自訂layoutSubviews都會導致另一個布局傳遞,那麼你將會陷入一個無限迴圈中。 

如:

 

iOS中AutoLayer自動布局流程及相關方法【轉】

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.