Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create constraints programmatically in Swift?

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?

like image 397
Cesare Avatar asked Jan 31 '15 14:01

Cesare


People also ask

How do I give a constraint to button programmatically in Swift?

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.

How do I create a constraint in Swift?

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.


1 Answers

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)
like image 143
picciano Avatar answered Oct 20 '22 03:10

picciano