简体   繁体   English

自动布局 Xcode

[英]Auto Layout Xcode

I'm a beginner having some difficulty understanding Auto layout constraints.我是一个初学者,很难理解Auto layout约束。 For each object placed in storyboard, do I have to specify width, height, along with both leading and trailing constraints to avoid an error message?对于放置在 storyboard 中的每个 object,我是否必须指定宽度、高度以及前导和尾随约束以避免出现错误消息?

For any view to be rendered accurately, the system needs to know, unambiguously, it's - position and dimension.对于要准确渲染的任何视图,系统需要明确地知道它是 - position 和尺寸。

Consider a simple scenario where you are trying to place a 'rectangle' of height 'Y' and width 'X' at the center of the screen, auto layout needs to know this intension.考虑一个简单的场景,您试图在屏幕中心放置一个高度为“Y”和宽度为“X”的“矩形”,自动布局需要知道这个意图。 You convey this by setting 4 constraints:您可以通过设置 4 个约束来传达这一点:

  1. Height constraint高度约束
  2. Width constraint宽度约束
  3. Vertically in container constraint (or centerYAnchor)垂直在容器约束(或 centerYAnchor)
  4. Horizontally in container constraint (or centerXAnchor)在容器约束(或 centerXAnchor)中水平

Any more or any less number of constraints would likely add ambiguity in terms of positioning or dimension.任何更多或更少数量的约束都可能会在定位或尺寸方面增加歧义。

In another example, where your 'rectangle' needs to be always 10 points from all edges of the parent view, you simply need to specify -在另一个示例中,您的“矩形”需要始终距离父视图的所有边缘 10 个点,您只需指定 -

  1. Leading Anchor of rectangle to be 10 points with respect to (wrt) leading anchor of the parent view矩形的前导锚相对于父视图的(wrt)前导锚为 10 个点
  2. Trailing anchor of rectangle to be -10 points wrt the trailing anchor of the parent view矩形的尾随锚点为 -10 点 wrt 父视图的尾随锚点
  3. Top anchor of rectangle to be 10 points wrt the top anchor of the parent view矩形的顶部锚点是父视图的顶部锚点的 10 个点
  4. Bottom anchor of the rectangle to be -10 points wrt the bottom anchor of the parent view矩形的底部锚点为 -10 点,相对于父视图的底部锚点

Note that trailing anchor and bottom anchor are negative because you are placing the child view anchors before the respective origins of those parent anchors.请注意,尾随锚点和底部锚点是负数,因为您将子视图锚点放置在这些父锚点的各自原点之前。 Also, you don't need to specify height or width in this case because the given constraints implicitly specify it dynamically with respect to the device dimensions.此外,在这种情况下,您不需要指定高度或宽度,因为给定的约束隐含地根据设备尺寸动态指定它。

These are just 2 very simple scenarios but if you try rendering and playing around using this logic (programatically or via storyboard), it'll make things clearer.这些只是 2 个非常简单的场景,但是如果您尝试使用此逻辑(以编程方式或通过情节提要)进行渲染和玩耍,它会让事情变得更清晰。

But really, this just scratches the surface.但实际上,这只是表面上的问题。 To actually dive deep, I recommend digging in with this section in the auto layout documentaion - ' Anatomy of a constraint '要真正深入研究,我建议深入研究自动布局文档中的本节 - “ 约束剖析

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM