Connor Neville Connor Neville - 1 year ago 78
Objective-C Question

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.

Answer Source

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

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

        item: myButton,
        attribute: .Width,
        relatedBy: .Equal,
        toItem: nil,
        attribute: .NotAnAttribute,
        multiplier: 1.0,
        constant: 200))