0

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

General Grievance
  • 4,555
  • 31
  • 31
  • 45
itMaxence
  • 1,230
  • 16
  • 28

2 Answers2

1

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.

itMaxence
  • 1,230
  • 16
  • 28
0

Try using self.view.translatesAutoresizingMaskIntoConstraints = false before adding the constraints programmatically.

Pranay Chander
  • 461
  • 5
  • 12
  • Thank you for passing by! I'm already doing this in the code indeed , the question is more about finding the right constraint rather than fixing a non working constraint. For short answers like this one, you might prefer using the comment section, also to improve quality of your posts/comments you might want to often use `code syntax` style and other layout text modifications – itMaxence May 26 '20 at 09:48