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!
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.
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
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With