Search code examples
iosswiftnslayoutconstraint

Get constraint of uibutton programmatically


I have 4 buttons in Storyboard with BottomSpace and Horizontal Alignment constraints. Is there a way to access those constraints constants without linking them as outlets? I want to update those constants when the user press a button so the ideal case in pseudocode would be:

func buttonPressed(_ button: UIButton) {
      button.bottomSpaceConstraint.constant += 10
      button.horizontalAlignment.constant += 10
}

Thank you in advance!


Solution

  • To expand on Stormsyder's answer, there is a much cleaner way to do the same thing using the filter method. See the following:

    let bottomConstraint = button.superview!.constraints.filter({ $0.firstAttribute == .bottom && $0.firstItem == button }).first!
    let horizontalAllignmentConstraint = button.superview!.constraints.filter({ $0.firstAttribute == .centerX && $0.firstItem == button }).first!
    

    Note this will crash if those constraints don't exist so make sure they do or unwrap safely.