Search code examples
iosobjective-cautolayout

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

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