54

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

ryo
  • 2,009
  • 5
  • 24
  • 44

1 Answers1

128

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
KlimczakM
  • 12,576
  • 11
  • 64
  • 83
  • 2
    Thank you very much for your response! I try to do your code. But I can't achieve what I want, because of `self.view!`. I fixed `self.view!` in my case. But I use Mr. Andrew Schreiber's way in existing "Can i change multiplier property for NSLayoutConstraint?" It did works well. I needed to search for it more. – ryo May 18 '16 at 15:07
  • 4
    How are you compiling when you are placing a logical statement as an argument? `addConstraint(self.constraintToChange = newConstraint)`? – ScottyBlades Aug 29 '18 at 07:16
  • `self.constraintToChange = newConstraint` doesn't compile, the whole example doesn't work – Vyachaslav Gerchicov Apr 11 '19 at 13:47
  • 2
    crashing the app in swift4.2 – Paresh. P Apr 26 '19 at 10:31
  • @Paresh.P I've updated the answer and it's fixed. – KlimczakM Jul 30 '19 at 06:52
  • 7
    It is crashing - "'Unable to install constraint on view. Does the constraint reference something from outside the subtree of the view? That's illegal." – iGatiTech Sep 26 '19 at 04:20
  • Now working before iOS 12. – yildirimatcioglu Apr 02 '21 at 18:50
  • 1
    The example crash and does not work – JhonnyTawk Apr 14 '21 at 19:27
  • 3
    In addition, for iOS 8 or later, it is better to use `constraint.isActive = true/false` instead of `removeConstraint` and `addConstraint` method. The API says "When developing for iOS 8.0 or later, set the constraint’s isActive property to true instead of calling the addConstraint(_:) method directly. The isActive property automatically adds and removes the constraint from the correct view." – Zhou Haibo May 30 '21 at 06:45
  • Short sweet and perfect solution. – Krutika Sonawala Jun 29 '21 at 05:41