iOS - Change the multiplier of constraint by Swift [duplicate]

How to change the multiplier of a constraint by using Swift.

someConstraint.multiplier = 0.6 // error: 'multiplier' is get-only property

I would like to know how to change the multiplier in code (Swift).


Since multiplier is a read-only property and you can't change it, you need to replace the constraint with its modified clone.

You can use an extension to do it, like this:

Swift 4/5:

extension NSLayoutConstraint {
    func constraintWithMultiplier(_ multiplier: CGFloat) -> NSLayoutConstraint {
        return NSLayoutConstraint(item: self.firstItem!, attribute: self.firstAttribute, relatedBy: self.relation, toItem: self.secondItem, attribute: self.secondAttribute, multiplier: multiplier, constant: self.constant)
    }
}

Usage:

let newConstraint = constraintToChange.constraintWithMultiplier(0.75)
view.removeConstraint(constraintToChange)
view.addConstraint(newConstraint)
view.layoutIfNeeded()
constraintToChange = newConstraint