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 constrain
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
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))
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.
How about using Layout Anchors?
myView.widthAnchor.constraintEqualToConstant(29).isActive = true
Rather than looking for an explicit height (28), a better idea would be to look for a height
constraint…
loginButton.constraints.first(where: { $0.firstAttribute == .height })?.constant = 40