Autolayout的一点理解

hgrd6944 8年前

来自: http://blog.csdn.net//likendsl/article/details/49332273


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