ios - 什么时候必须在 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 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/

相关文章:

ios - 在 Swift 中使用 UIPasteBoard 将文本从 UITextView 复制到剪贴板

swift - 快速禁用 UIwebView textField 中的键盘

ios - 在 UITableView 中单击时更改 UIButton 颜色和文本

ios - 如何禁用与 UIBarButtonItem 的用户交互?

ios - 为什么 Date Picker 背景颜色变化在运行时不可见?

ios - 呈现模态视图 Controller ,但不隐藏导航栏

ios - 不可编辑的 UITextView 左对齐 RTL(阿拉伯语、希伯来语等)文本

ios - Swift:将文件导入桥接 header 时出现段错误 11

ios - 无法访问 WeatherKit

php - iOS登录-此代码正确/安全吗?如何检查用户是否已经登录?