Search code examples
iosswiftautolayoutnslayoutconstraint

How to programmatically add constraint center with multiplier


I do use multiplier with center constraints in the storyboard, now I want to do the same programmatically but can't figure out how to.

No, this thread does not help since the accepted answer is a workaround that would not auto resize if the superview size happens to change later on.

The storyboard center X constraint:

enter image description here

What I've tried without success:

// Does not exist
buttonLeft.centerXAnchor.constraint(equalTo: centerXAnchor, multiplier: 0.5).isActivate = true

// error shown:
// Cannot convert value of type 'NSLayoutXAxisAnchor' to expected argument type 'NSLayoutConstraint.Attribute'
let newConstraint = NSLayoutConstraint(item: self, attribute: centerXAnchor, relatedBy: .equal, toItem: buttonLeft, attribute: centerXAnchor, multiplier: 0.5, constant: 0)

Is it possible?

  • Yes: how?
  • No: do you have any explaination of why wouldn't it be possible programmatically? Does this thing is a syntaxic sugar hidding something more complexe? I'm lost..

And yep, it works as expected when this constraint is set using the storyboard


Solution

  • So it's possible, I missused the centerXAnchor instead of using .centerX

    Also the order in which I called each item was not correct:

    // Not Working
    NSLayoutConstraint(item: self, attribute: centerXAnchor, relatedBy: .equal, toItem: buttonLeft, attribute: centerXAnchor, multiplier: 0.5, constant: 0)
    
    // Working
    NSLayoutConstraint(item: buttonLeft, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 0.5, constant: 0)
    

    Though I could not find any way to create the constraint using the anchors methods.