Autolayout的一點理解

AutoLayout的核心思想:

Auto Layout 的本質是依靠 某幾項約束條件 來達到對某一個元素的確定性定位。我們雖然可以在某個地方只使用一個約束,以達到一個小小的目的,例如防止內容遮蓋、防止邊界溢出等。但最佳實踐證明,如果把頁面上每一個元素的位置都用 Auto Layout 進行 “嚴格約束” 的話,那麼 Auto Layout 可以幫我們省去非常多的計算 frame 的代碼。

簡單來說,嚴格約束就是對某一個元素的確定性定位,讓它在任一屏幕尺寸下都有着唯一確定的位置。這裏的確定性定位不是定死的位置,而是對一個元素 完整的約束條件,即在特定屏幕下,這個視圖元素的展現具有唯一確定性

AutoLayout的類型:

這個大致分兩類:在xcode7,xib的下面有四個選項,其中中間兩個選項就是這兩類的集中選擇:

1.對齊選項       Edge操作的元素主要針對的是x,y,center,baseline)

  a.相對於父元素        Top Edges,Bottom EdgesLeadingEdgesTrailingEdges,Center,Baseline

  b.相對於相鄰元素    Top Edges,Bottom EdgesLeading EdgesTrailingEdges,Center,Baseline

2.邊間距選項    Space:(操作的元素主要針對的是Δx,Δy,width,height

  a.相對於父元素        Top Space ,Bottom Space,Leading Space,Trailing Space,Widths,Heights,Ratio

  b.相對於相鄰元素    Top Space ,Bottom Space,Leading Space,Trailing Space, Widths,Heights,Ratio

3.內容適配選項

   a.Compression Resistance

   b.Content Hugging

   c.優先級  

簡單的來說Compression Resistance 設置view有多大意願(優先級),願意壓縮裏面的內容。Content Hugging設置view 有多大願意(優先級),願意顯示裏面內容之外的部分。

stackoverflow上面有一個很清晰的通過UIButton解釋的[例子]:

Quick summary of the concepts:

  • Hugging => content does not want to grow
  • Compression Resistance => content does not want to shrink

and an example:

Say you've got button like this:

[       Click Me      ]

and you've pinned the edges to a larger superview with priority 500. //superview priority 500是以下使用的前提.

Then, if Hugging priority > 500 it'll look like this:

[Click Me]

If Hugging priority < 500 it'll look like this:

[       Click Me      ]

If superview now shrinks then, if the Compression Resistance priority > 500, it'll look like this

[Click Me]

Else if Compression Resistance priority < 500, it could look like this:

[Cli..]

If it doesn't work like this then you've probably got some other constraints going on that are messing up your good work!

E.g. you could have it pinned to the superview with priority 1000. Or you could have a width priority. If so, this can be helpful:

Editor > Size to Fit Content

AutoLayout的視圖顯示的階段:

使用AutoLayout之後,把view顯示到屏幕上面大體分成3步。

  • Update constraints
  • Layout views
  • Display

一般來說layoutSubviews負責佈局,比如調整View之間的距離,大小,drawRect負責繪製,比如使用什麼顏色。而AutoLayout則是在layout之前增加了一個設定約束的過程,也就是上面提到了update constraints








發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章