以编程方式更改中心 X / Y 对齐约束的乘数

Programmatically Change multiplier of Alignment Constraint of Center X / Y

如何以最简单的方式以编程方式更改乘数?

对于Swift 2.0

所以对于Y,如果你将图像的顶部设置为等于0的常量到superView的顶部。然后输入此代码:

@IBOutlet weak var topc: NSLayoutConstraint!


let heightOfSuperview = self.view.bounds.height
topc.constant = heightOfSuperview * 0.90 // this has the same effect as multiplier  

这相当于 Center.y 乘数 = 0.9:1

我尝试使用扩展但它不起作用,但更改为全局实用程序函数并且它对我有用:

public class func changeMultiplier(constraint: NSLayoutConstraint, multiplier: CGFloat) -> NSLayoutConstraint {
    let newConstraint = NSLayoutConstraint(
        item: constraint.firstItem,
        attribute: constraint.firstAttribute,
        relatedBy: constraint.relation,
        toItem: constraint.secondItem,
        attribute: constraint.secondAttribute,
        multiplier: multiplier,
        constant: constraint.constant)

    newConstraint.priority = constraint.priority
    NSLayoutConstraint.deactivateConstraints([constraint])
    NSLayoutConstraint.activateConstraints([newConstraint])
    return newConstraint
}

简单的答案,不需要扩展。我尝试过我的情况,对我来说效果很好。

因为乘数是一个只能获取的 属性,我们可以简单地按以下方式设置乘数:

yourConstraintOutlet.setValue(yourDesiredMultiplierValue, forKey: "multiplier")

yourConstraintOutlet.setValue(0.75, forKey: "multiplier")

无需编写扩展或乘以父视图的高度。