iOS NSLayoutConstraint Fixed Width using constraintWithItem

前端 未结 5 501
無奈伤痛
無奈伤痛 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:55

    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.

提交回复
热议问题