Connor Neville Connor Neville - 3 months ago 13
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

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))