SwiftUI: How to create awesome flip effect with Rotation 3D Effect in 3 seconds

I feel great to be able to create incredibly cool effects with just a few simple lines of code with SwiftUI. Today, let’s learn about flipping animation. For reference, flipping animation can be implemented in several ways. Typically, it can be implemented using geometry effect, but it can be easily implemented with 3D Rotation Effect.

Let’s look at the code first!

This simple code will trigger 3D rotation effect when user clicks card(HStack). When @State flipped is toggled, the value of Angle is changed.

How do I apply rotation3DEffect?

This is the code that flips cards.

  1. You need @State variable to keep track of its flipped state.
  2. Attach .rotation3DEffect() with flag(@State var flipped: Bool) and change Angle accordingly.
  3. In order to create animation effect, apply implicit animation to the view with .animation(.default, value: flipped).
  4. When user taps on the view, toggle flipped to trigger animation.

That’s all you need to do to create this awesome animation.

Why Applying rotationEffect again?

You should apply rotation3DEffect in order to re-rotate view. Otherwise, your view will be shown upside-down.

Changing x axis

When you give x axis value, it will turn from bottom to top.

Changing y axis

When you give x axis value, it will turn from right to left.

Changing z axis

This only rotates card.

Conclusion

  1. Create @State var flipped to keep track of your view’s flipped state.
  2. Apply rotation3DEffect to your view
  3. Apply rotation3DEffect again to your target view (Re-rotate view)
  4. Apply Implicit Animation

That’s all!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
KD Knowledge Diet

KD Knowledge Diet

Software Engineer, Mobile Developer living in Seoul. I hate people using difficult words. Why not using simple words? Keep It Simple Stupid!