Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ios

swift

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).

like image 733
ryo Avatar asked May 18 '16 08:05

ryo


People also ask

How do I change the constraint multiplier in Swift?

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

Can I change multiplier property for NSLayoutConstraint?

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.

What is NSLayoutConstraint?

The relationship between two user interface objects that must be satisfied by the constraint-based layout system.

What is multiplier in Swift?

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.


1 Answers

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
like image 89
KlimczakM Avatar answered Oct 20 '22 09:10

KlimczakM