iOS NSLayoutConstraint Fixed Width using constraintWithItem

前端 未结 5 495
無奈伤痛
無奈伤痛 2021-02-02 06:37

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

5条回答
  •  悲&欢浪女
    2021-02-02 06:48

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

提交回复
热议问题