Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS NSLayoutConstraint Fixed Width using constraintWithItem

I'd like to set a constraint to give a UIButton a fixed (constant) width programmatically. I know I can do this with constraintsWithVisualFormat, but I've been using constraintWithItem for all of my constraints in code. I was wondering for the sake of curiosity/consistency if there was any way to do this with constraintWithItem.

like image 614
Connor Neville Avatar asked Dec 29 '14 00:12

Connor Neville


People also ask

How do you set the multiplier in NSLayoutConstraint?

You have to remove the old NSLayoutConstraint and replace it with a new one to modify it. However, since you know you want to change the multiplier, you can just change the constant by multiplying it yourself when changes are needed which is often less code.

How do you add constraints in Xcode?

To create constraints select the button and click the Align icon in the auto layout menu. A popover menu will appear, check both “Horizontal in container” and “Vertically in container” options to center the button on the screen. Then click the “Add 2 Constraints” button.

How do I enable constraints in Swift?

addConstraint(constY); var constW:NSLayoutConstraint = NSLayoutConstraint(item: new_view, attribute: NSLayoutAttribute. Width, relatedBy: NSLayoutRelation. Equal, toItem: new_view, attribute: NSLayoutAttribute. Width, multiplier: 1, constant: 0); self.


2 Answers

Found my solution. Just set the other object to nil, and the other attribute to NSLayoutAttributeNotAnAttribute (this was what I failed to think of) and use the constant parameter for the fixed width:

[self addConstraint:[NSLayoutConstraint constraintWithItem:myButton
      attribute:NSLayoutAttributeWidth 
      relatedBy:NSLayoutRelationEqual 
      toItem:nil 
      attribute:NSLayoutAttributeNotAnAttribute 
      multiplier:1.0 
      constant:200]];

Edit: since this answer still seems to get a fair share of views, I thought I'd add the Swift syntax:

self.addConstraint(NSLayoutConstraint(
        item: myButton,
        attribute: .width,
        relatedBy: .equal,
        toItem: nil,
        attribute: .notAnAttribute,
        multiplier: 1.0,
        constant: 200))
like image 170
Connor Neville Avatar answered Oct 08 '22 19:10

Connor Neville


How about using Layout Anchors?

myView.widthAnchor.constraintEqualToConstant(29).isActive = true
like image 20
Lukas Batteau Avatar answered Oct 08 '22 19:10

Lukas Batteau