iOS NSLayoutConstraint Fixed Width using constraintWithItem

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

    In swift:

    let width = 120
    let constraint = NSLayoutConstraint(
        item: myView,
        attribute: .width,
        relatedBy: .equal,
        toItem: nil,
        attribute: .notAnAttribute,
        multiplier: 1.0,
        constant: width)
    NSLayoutConstraint.activateConstraints([constraint])
    

    Then you can change constraint's constant value

    constraint.constant = width * 2
    

提交回复
热议问题