我们知道Masonry是基于NSLayoutConstraint封装的一个轻量级的布局框架 拥有自己的描述语法 采用更优雅的链式语法封装自动布局 简洁明了 并具有高可读性 而且同时支持 iOS 和 Max OS X。
为了弄清楚它的原理我们先来看一下苹果官方文档 NSLayoutConstraint
constraint:约束,不仅仅用来表示控件之间的关系,还可以设置控件的属性的关系(>、>=、=、<=、<),还可以用来表示优先级priorities(1-1000,required为1000)
当我们添加了必要的约束之后,Auto Layout 就会在这些约束中按照优先级从高到低的去找实现这个布局的解决方法(往往一个控件的布局不止一个解决方法)。如果没有找到合理方法,会尽可能的实现你想要的结果。更多的约束例子详见Stack Views 和Understanding Auto Layout
这里有一个苹果官方用swift写的自动布局的例子Auto Layout Cookbook
Views with Intrinsic Content Size :(view固有内容的大小)
label、textField、button不需要特意指定宽高,除非你有什么特殊要求,UIView没有内容需要指定宽高,UIView如果只想设置坐标不设置大小详见iOS进阶指南试读之UI篇。 和
Setting the Placeholder Intrinsic Size for a Custom View
imageView布局:
For example, an empty image view does not have an intrinsic content
size. As soon as you add an image, though, its intrinsic content size is
set to the image’s size.
textView布局:
A text view’s intrinsic content size varies depending on the content, on
whether or not it has scrolling enabled, and on the other constraints
applied to the view. For example, with scrolling enabled, the view does
not have an intrinsic content size. With scrolling disabled, by default
the view’s intrinsic content size is calculated based on the size of the
text without any line wrapping. For example, if there are no returns in
the text, it calculates the height and width needed to layout the
content as a single line of text. If you add constraints to specify the
view’s width, the intrinsic content size defines the height required to
display the text given its width.
Content Hugging/Content Compression(抗伸展性,抗压缩性)
约束默认:content hugging = 250(priority) ,compression resistance = 750(priority),因此拉伸view比压缩view容易。更多信息去看Setting Content-Hugging and Compression-Resistance Priorities
苹果推荐尽量使用固有内容大小来布局。这样能减少模糊和冲突的约束,但是你要自己管理Content Hugging and Compression Resistance priorities.
guidelines
Attributes:
参考文献:Masonry使用注意篇
Masonry -- 使用纯代码进行iOS应用的autolayout自适应布局