在iOS中,autoresizing、AutoLayout和constraints有什么区别?

32

在阅读苹果文档时,我发现了关于自动调整大小、AutoLayout和约束的参考。在代码中使用这些技术有什么区别?在iOS 9中以编程方式应用这些技术的正确方法是什么?

1个回答

70

这里实际上只有两件事:

  • 自动调整大小
  • 自动布局

自动调整大小基本上是一个集体术语,用于描述苹果公司引入的旧方法,以使开发人员能够构建动态布局。这里需要解决的头等大事是屏幕旋转。因为当屏幕被旋转(或者以其他方式调整大小)时,屏幕中的子视图很可能会在新调整大小的父视图中保留不正确的frame(位置和大小)。为了解决这个问题,苹果公司引入了一系列可枚举属性(称为Autoresizing Masks),告诉父视图以特定的方式处理子视图。其中包括:

  • 灵活的宽度/高度,导致子视图扩展到最大的可用宽度/高度

  • 灵活的前导/尾随/顶部/底部空间,允许特定边缘是可变的,等等。

一个视图可以包含任意组合的这些enum属性。

这种方法是不足的,因为除了其他缺点之外,它没有规定视图应该如何相对于其其他兄弟视图进行布局(如果那是一个动词的话)。它还需要大量额外的编码来手动调整视图大小以适应方向变化。

Here's where AutoLayout entered the picture. Apple built a framework which worked on the basis of constraints - rules that could be applied on views and between views, that would determine how a view would be sized in variable screen sizes. These constraints are structured in a class called NSLayoutConstraint, and each instance (constraint) of this class has the following important properties:
  • The item (view) on which the constraint is applied
  • The property of the view (height, width, leading edge, trailing edge, and so on) that the constraint is applicable to
  • The second item (a sibling or a child or a parent view) to which the constraint is related
  • The second item's attribute
  • The multiplier on the constraint: useful in order to specify ratio based constraints
  • A value (or constant) of the constraint: interestingly, the only property of a constraint that can be changed after instantiation.

A simple example of an NSLayoutConstraint, stated prosaically is: a view's width will be half the the width of its superview multiplied by 60%.

Your AutoLayout based UI would consist of many such constraints, which will all work together to express an unambiguous and non-conflicting UI Layout.

现在,AutoLayout引擎与屏幕上的视图进行交互,根据需要调用AutoLayout消息,例如layoutSubviews以便在屏幕发生更改时自动调整(布局)视图大小,例如方向更改、父视图大小更改等。
约束通常是通过InterfaceBuilder(.xib和.storyboard文件)添加的,但通过代码添加约束遵循相同的原则:创建NSLayoutConstraint实例并将其添加到适用的最高视图(例如,如果存在子视图和父视图之间的约束,则应将约束添加到父视图。如果存在两个子视图之间的约束,则再次将其添加到父视图)。
苹果公司的AutoLayout指南API文档和介绍性WWDC视频对于学习AutoLayout来说都非常好,这些是了解更多信息的最佳途径。

6
我正在写答案,但你的答案更好。干得漂亮! - mattsven
补充一下,UIStackView类 https://developer.apple.com/reference/uikit/uistackview 已经出现了。@Andrew - finneycanhelp
1
@Vinod 这个答案确实很好,但也许你还可以提到NSLayoutAnchor,因为这是苹果最近在NSLayoutConstraint之上新增的改进。同时像@finneycanhelp所说的,UIStackView也是快速原型设计UI的绝佳选择。 - HuaTham
@Vinod 我认为你应该将优先级属性添加到NSLayoutConstraint类的重要属性列表中。通过组合不同优先级的约束,您可以实现很多功能,甚至可以通过更改其优先级来动画化视图。 (例如,将定义视图高度的约束的优先级从高变为低,允许您在屏幕上出现/消失视图;-)。是可以动画化的 :-)。顺便说一句,非常好的答案,谢谢。 - Vojta

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接