Wayne's blog
design, development, hobbies

Flippin' Cards

The other day I needed to represent a physical 2-sided card in a design. The previous design had the user selecting the front or back of the card, with the new view being presented showing that side of the card. We can do better. Let’s make this more interactive!

Design

The face card was scanned and traced in Illustrator, then exported as SVG into Figma.

Figma Cards

Xcode

A Single View Application will do fine for this demo. Our card will be a tappable button. Add in an outlet for the card:

@IBOutlet weak var btnCard: UIButton!
var isOpen = false 

In the viewDidLoad() method, further customize the card button:

override func viewDidLoad() {
	...
	btnCard.adjustsImageWhenHighlighted = false
	btnCard.layer.cornerRadius = 11.0
	btnCard.layer.shadowColor = UIColor.gray.cgColor
	btnCard.layer.shadowOffset = CGSize(width: 0.0, height: 10.0)
	btnCard.layer.shadowRadius = 12.0
	btnCard.layer.shadowOpacity = 0.7
}

And finally, let’s add the action to the button tap, swapping the image, and animating the view’s transform:

  @IBAction func btnFlip(_ sender: Any) {
    if isOpen {
      isOpen = false
      let image = UIImage(named: "cardBack")
      btnCard.setImage(image, for: .normal)
      UIView.transition(with: btnCard, duration: 0.3,
       options: .transitionFlipFromLeft, animations: nil, completion: nil)
    } else {
      isOpen = true
      let image = UIImage(named: "cardFront")
      btnCard.setImage(image, for: .normal)
      UIView.transition(with: btnCard, duration: 0.3, options: .transitionFlipFromRight, animations: nil, completion: nil)
    }
  }

We’re basically using a built-in animation called .transtitionFlipFromRight and .transitionFlipFromLeft to simulate the flipping. The animation duration is set to 0.3 seconds, and swaps the image using the isOpen binary flag. ddd

Result

Card Flip Animation

If you’d like to take a look at some of the other free animation curves, settings and transition presets UIKit provides, take a look at Apple’s documentation.

Conclusion

Today we discussed a simple way to flip a card or any view for that matter. Using nothing but built-in UIKit animation presets.

Feel free to follow me on Twitter and ask your questions related to this post. Thanks for reading and see you next post.