IOS - Change Constraint Multiplier to Swift

How to change constraint multiplier using Swift.

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

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

+21
ios swift
source share
1 answer

Since multiplier is read-only and you cannot change it, you need to replace the restriction with its modified clone.

You can write an extension for this, for example:

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

Using:

 let newConstraint = constraintToChange.constraintWithMultiplier(0.75) view.removeConstraint(constraintToChange) view.addConstraint(newConstraint) view.layoutIfNeeded() constraintToChange = newConstraint 
+53
source share

All Articles