Changing constraints of a UIButton

I am making a card game where you choose between two cards to flip over. When the user flips the card it’s moves to the center of the screen so the whole card image is shown as it is too large to fit in the original position. My problem is when the user flips the card back over it does not move back to it’s original position and I cannot figure out how to program it to do so. Is there an easy way to revert the change of constraints when the button is pressed the second time?

Changing constraints of a UIButton

  • Do you change constraints of Button or of image ?
  • Could you show code ?
  • How did you define constraints for imageView ?
  • How do you move image to the center ? By modifying constraints ?

You could:

  • create constraints in IB for ImageView, those that will be needed in the 2 positions
  • create IBOutlets for them
  • keep original values in constants in your code ; and define values for center position
  • when you tap on the button, you adapt the needed constraints constant to their new value or activate / deactivate as needed.
  • when you tap again, restore the original values you have defined

Refer to Xcode doc for NSLayoutConstraint.

Oops: that's for UIKit, not SwiftUI. In SwiftUI, I would:

  • define the 2 views for the 2 positions
  • have a Bool state var to tell which one to show
  • toggle this var in the button action.
Changing constraints of a UIButton
 
 
Q