Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 493
iDec Avatar asked Nov 04 '16 12:11

iDec


2 Answers

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.

like image 92
Jacob King Avatar answered Sep 19 '22 18:09

Jacob King


Answer for swift 3:

func buttonPressed(_ button: UIButton) {
    for constraint in button.superview!.constraints {
        if constraint.firstAttribute == .bottom {
            constraint.constant += 10
        }
    for constraint in button.constraints {
        if constraint.firstAttribute == .centerY {
            constraint.constant += 10
        }
    }
}
like image 24
Stormsyders Avatar answered Sep 19 '22 18:09

Stormsyders