How to create software restrictions in Swift?

I am trying to set the width UIButtonusing 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 is stretched too much; probably because toItem: self.view. I tried to change the constraint constant, but that didn't change anything.

How to properly configure this restriction so that it has a width of 100?

+4
source share
2 answers

You were close. A restriction should have only one element, since it does not apply to another element.

constraintButtonPlayWidth = NSLayoutConstraint (item: buttonPlay,
    attribute: NSLayoutAttribute.Width,
    relatedBy: NSLayoutRelation.Equal,
    toItem: nil,
    attribute: NSLayoutAttribute.NotAnAttribute,
    multiplier: 1,
    constant: 100)
self.view.addConstraint(constraintButtonPlayWidth)
+22
source

toItem should be set to zero so your code looks like this:

constraintButtonPlayWidth = NSLayoutConstraint (item: buttonPlay,
    attribute: NSLayoutAttribute.Width,
    relatedBy: NSLayoutRelation.Equal,
    toItem: nil,
    attribute: NSLayoutAttribute.Width,
    multiplier: 1,
    constant: 100)
self.view.addConstraint(constraintButtonPlayWidth)
+1
source

All Articles