何时必须在iOS自动布局中使用优先级?

何时必须在iOS自动布局中使用优先级?,ios,objective-c,swift,uiview,ios-autolayout,Ios,Objective C,Swift,Uiview,Ios Autolayout,使用iOS AutoLayout,您将执行以下操作: self.view.addConstraint(NSLayoutConstraint(item: label, attribute: .Width, relatedBy: .Equal, toItem: self.view, attribute: .Width, multiplier: 0.3, constant: 0)) 还可以为每个布局约束使用优先级 什么时候我必须在iOS自动布局中使用优

使用iOS AutoLayout,您将执行以下操作:

self.view.addConstraint(NSLayoutConstraint(item: label, 
   attribute: .Width, 
   relatedBy: .Equal, 
   toItem: self.view, 
   attribute: .Width, 
   multiplier: 0.3, 
   constant: 0))
还可以为每个布局约束使用优先级


什么时候我必须在iOS自动布局中使用优先级?

您可以使用它来近似条件逻辑

例如,我有一个裁剪视图(想象一个面轮廓的圆形切口)。如果图像是纵向的,我希望圆圈靠近顶部,但是如果图像是横向的,就没有空间让它偏离中心,这就没有意义了

为了解决这两种情况,我首先设置了边界约束-覆盖应始终位于图像视图内(使用=边上的约束)。然后,我有另一个优先级较低的约束,表示理想情况下它将位于中心之上,但在该约束之下有一个后备约束,表示我希望它位于中心之上。最后两个约束会导致冲突,但布局引擎会选择最高优先级。在横向的情况下,上面的中心是不可能的,所以艾尔打破了这一点,留下了中心约束

另一个例子——也是下面的代码片段中的一个例子——是我希望我的覆盖层使用尽可能多的空间,同时保持适当的纵横比。这意味着,虽然我的外部约束是绝对的,但我宣布理想的裁剪帧位于边界处,因为我知道一次只能满足一组,但高宽比优先。铝然后打破尽可能多的-这是两个,在每个方向,留下其他两个在机智。如果没有这一点,这个问题将有许多可能的解决办法

在我的实际代码中,我将它们捕获为一个约束数组。每个都由一个惰性实例变量创建:

    self.addConstraints([

        // absolute constraints
        self.leftMarginConstraint,
        self.rightMarginConstraint,
        self.topMarginConstraint,
        self.bottomMarginConstraint,
        self.aspectRatioConstraint,
        self.constrain(self.maskContainer, self, .CenterX, .Equal),

        // hug the edges as much as possible, but only two of the four will be used
        self.constrain(self.maskContainer, self, .Left, .Equal, priority:900),
        self.constrain(self, self.maskContainer, .Right, .Equal, priority:900),
        self.constrain(self.maskContainer, self, .Top, .Equal, priority:900),
        self.constrain(self, self.maskContainer, .Bottom, .Equal, priority:900),

        // try for above center, but accept vertically centered
        self.constrain(self.maskContainer, self, .CenterY, .Equal, priority:800, multiplier:0.8),
        self.constrain(self.maskContainer, self, .CenterY, .Equal, priority:500),
        ])

在autolayout中,当两个约束和情节提要发生冲突时,通常使用优先级,以混淆哪个约束是正确的。如果您将优先级设置为高于,则使用高于第二个的最高优先级约束。

我没有了解最后两个约束。请您解释一下它们是如何工作的。也许您从您目前了解的内容开始,我在上面的第三段中描述了它们。这种解释没有意义。我不明白你所说的。