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.
Solution 1:
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))
Solution 2:
How about using Layout Anchors?
myView.widthAnchor.constraintEqualToConstant(29).isActive = true
Solution 3:
In swift:
let width = 120
let constraint = NSLayoutConstraint(
item: myView,
attribute: .width,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1.0,
constant: width)
NSLayoutConstraint.activateConstraints([constraint])
Then you can change constraint's constant value
constraint.constant = width * 2
Solution 4:
Here's a simple code for button with fixed width.
visual format:-
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H: [myButton(==50)]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(myButton)]];
Use this code for constraint using visual format where self.view is your button's superview and myButton is name of your button and 50 is the width of myButton. You can change these values according to get the desired constraint.
constraintWithItem format:-
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:myButton attribute: NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute: NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:50.0]];
Use this code for constraint using constraintWithItem format where self.view is your button's superview and myButton is name of your button and 50 is the width of myButton. You can change these values according to get the desired constraint.