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.
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.
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.
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.
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))
How about using Layout Anchors?
myView.widthAnchor.constraintEqualToConstant(29).isActive = true
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