1

I'm trying to scale constraints' values just after setting them up in a such way:

@IBDesignable
class ScaledConstraint: NSLayoutConstraint {
    @IBInspectable var constantValue: CGFloat = 0 { didSet { constantValueDidSet() } }

    func constantValueDidSet() {
        super.constant = (constantValue / 320) * UIScreen.main.bounds.width
    }
}

But that approach is forcing me to change IBInspectable variable for every constraint. I've tried to deal with it overriding default constant value but it works only when I set constant value from the code, and deals no effect when I'm setting it from the interface builder:

override var constant: CGFloat {
        set(newValue) {
            self.constant = (newValue / 320) * UIScreen.main.bounds.width
        }
        get {
            return self.constant
        }
    }

Is there a way to change constant value just after setting it from the interface builder without custom IBInspectable variable? Thanks in advance!

coldembrace
  • 549
  • 8
  • 19

1 Answers1

0

You have the ability to Outlet constraints from the storyboard into your View Controller, similarly to how you outlet UIView's and other View components, even though a bit more annoying to grab the outlet it self. (The answer Here shows you how to do it).

So one of your outlets would look like this:

@IBOutlet weak var myConstraint: NSLayoutConstraint!

To Which you can later call:

myConstraint.constant = 100 //Or whatever value you want

Afterwards, you should be sure to call:

view.layoutIfNeed()
Alan S
  • 594
  • 3
  • 13
  • Unfortunately, it's not the answer to my question. – coldembrace Aug 02 '19 at 12:53
  • @coldembrace I guess that is true, but in the end you can accomplish your objective with this method. You can programmatically calculate the constraint value you need and set it here without subclassing NSLayoutConstraint. The constant value you're saving can be saved in the view/ViewController. – Alan S Aug 06 '19 at 07:53
  • Yes, I know, but calculating constraint value programmatically is not my case, I need only storyboard solution to this – coldembrace Aug 06 '19 at 11:44
  • @coldembrace but isn't this your implementation choice? You have access to both solutions and it's up to you to decide which to use of course. But one will work and the other has clearly caused you issues. – Alan S Aug 06 '19 at 11:55
  • No, its not, I was asking about another solution using ONLY storyboard – coldembrace Aug 07 '19 at 08:41
  • @coldembrace, might I ask why you need an storyboard only solution? – Alan S Aug 07 '19 at 09:14