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 have to remove the old NSLayoutConstraint and replace it with a new one to modify it. However, since you know you want to change the multiplier, you can just change the constant by multiplying it yourself when changes are needed which is often less code.
The relationship between two user interface objects that must be satisfied by the constraint-based layout system.
Multiplier is there for creating Proportional Constraint. Auto Layout calculates the first item's attribute to be the product of the second item's attribute and this multiplier . Any value other than 1 creates a proportional constraint.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With