在阅读苹果文档时,我发现了关于自动调整大小、AutoLayout和约束的参考。在代码中使用这些技术有什么区别?在iOS 9中以编程方式应用这些技术的正确方法是什么?
在阅读苹果文档时,我发现了关于自动调整大小、AutoLayout和约束的参考。在代码中使用这些技术有什么区别?在iOS 9中以编程方式应用这些技术的正确方法是什么?
这里实际上只有两件事:
自动调整大小基本上是一个集体术语,用于描述苹果公司引入的旧方法,以使开发人员能够构建动态布局。这里需要解决的头等大事是屏幕旋转。因为当屏幕被旋转(或者以其他方式调整大小)时,屏幕中的子视图很可能会在新调整大小的父视图中保留不正确的frame
(位置和大小)。为了解决这个问题,苹果公司引入了一系列可枚举属性(称为Autoresizing Masks
),告诉父视图以特定的方式处理子视图。其中包括:
灵活的宽度/高度,导致子视图扩展到最大的可用宽度/高度
灵活的前导/尾随/顶部/底部空间,允许特定边缘是可变的,等等。
一个视图可以包含任意组合的这些enum
属性。
这种方法是不足的,因为除了其他缺点之外,它没有规定视图应该如何相对于其其他兄弟视图进行布局(如果那是一个动词的话)。它还需要大量额外的编码来手动调整视图大小以适应方向变化。
Here's where AutoLayout entered the picture. Apple built a framework which worked on the basis ofconstraints
- 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:
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
以便在屏幕发生更改时自动调整(布局)视图大小,例如方向更改、父视图大小更改等。NSLayoutConstraint
实例并将其添加到适用的最高视图(例如,如果存在子视图和父视图之间的约束,则应将约束添加到父视图。如果存在两个子视图之间的约束,则再次将其添加到父视图)。
NSLayoutAnchor
,因为这是苹果最近在NSLayoutConstraint
之上新增的改进。同时像@finneycanhelp所说的,UIStackView
也是快速原型设计UI的绝佳选择。 - HuaTham