使用 iOS AutoLayout 你会做类似的事情:
self.view.addConstraint(NSLayoutConstraint(item: label,
attribute: .Width,
relatedBy: .Equal,
toItem: self.view,
attribute: .Width,
multiplier: 0.3,
constant: 0))
您还可以为每个布局约束使用优先级。
我什么时候必须在 iOS AutoLayout 中使用优先级?
最佳答案
您可以使用它来近似条件逻辑。
例如,我有一个裁剪 View (想象一个面部轮廓的圆形切口)。如果图像是纵向的,我希望圆圈靠近顶部,但如果图像是横向的,就没有空间让它偏离中心,这样就没有意义了。
为了解决这两种情况,我首先设置了边界约束——叠加层应该始终在 ImageView 内(使用 <=/>= 对边缘的约束)。然后我有另一个较低优先级的约束,说理想情况下它会在中心上方,但在那个下方有一个后备约束,否则我希望它居中。最后两个约束会导致冲突,但布局引擎会选择最高优先级。在风景的情况下,中心上方是不可能的,所以 AL 打破了这一点,留下了中心约束。
另一个例子 - 也出现在下面的代码片段中,是我希望我的叠加层使用尽可能多的空间,同时保持适当的纵横比。这意味着虽然我的外部约束是绝对的,但我宣布理想的裁剪框在边界处,因为我知道一次只能满足一组,但纵横比优先。然后 AL 尽可能多地打破它 - 这是两个,在每个方向上,留下其他两个完好无损。否则,问题会有很多可能的解决方案。
在我的实际代码中,我将它们捕获为一组约束。每个都由惰性实例变量创建:
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),
])
关于ios - 什么时候必须在 iOS AutoLayout 中使用优先级?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30655121/