I am trying to set up the width of a UIButton
using this code:
constraintButtonPlayWidth = NSLayoutConstraint(item: buttonPlay,
attribute: NSLayoutAttribute.Width,
relatedBy: NSLayoutRelation.Equal,
toItem: self.view,
attribute: NSLayoutAttribute.Width,
multiplier: 1,
constant: 100)
self.view.addConstraint(constraintButtonPlayWidth)
But the button gets stretched too much; probably because toItem: self.view
. I tried modifying the constant of the constraint, but that didn't change anything.
How do I set up correctly this constraint so it actually has a width of 100?
Add the button in the view, give it constraints and as you are using constraints, you can skip the button. frame and add widthAnchor and heightAnchor . At last activate them and keep translatesAutoresizingMaskIntoConstraints as false . Also, it will be better if you can add proper names.
It's the laxest way to add constraints; you simply control-drag from any view to another view to set constraints between each other. The Auto Layout menu is another way to add constraints with ease. At the bottom-right corner of the Interface Builder editor, you should find five buttons as shown below.
You were close. The constraint only should have a single item since it is not relative to another item.
constraintButtonPlayWidth = NSLayoutConstraint (item: buttonPlay,
attribute: NSLayoutAttribute.Width,
relatedBy: NSLayoutRelation.Equal,
toItem: nil,
attribute: NSLayoutAttribute.NotAnAttribute,
multiplier: 1,
constant: 100)
self.view.addConstraint(constraintButtonPlayWidth)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With