Search code examples
swiftuiviewnslayoutconstraint

Cannot find constraint by id


I have a button with Center X Alignment Constraint and this constraint's identifier is "constBtnSound".

I'm trying to get this constraint with the following code but cannot find it.

for const in btnSound.constraints {
  if const.identifier == "constBtnSound" {
        ...
    }
}

Properties of the constraint:

enter image description here

All constraints of the button:

enter image description here


Solution

  • Here's what the UIView.addConstraint documentation says:

    The constraint must involve only views that are within scope of the receiving view. Specifically, any views involved must be either the receiving view itself, or a subview of the receiving view.

    Since button.superview is not button and is not a subview of button, the constraint cannot be held by button.

    Since button is a subview of button.superview, the constraint can be held by button.superview (or any ancestor of button.superview).

    However, instead of searching for the constraint by id, you could create an outlet for it:

    @IBOutlet var buttonXCenterConstraint: NSLayoutConstraint!
    

    Connect the outlet to the constraint in your storyboard.