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

KD Knowledge Diet
2 min readJun 18, 2022
Flipping Animation

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!

Code

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?

The code that actually flips card

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?

If you don’t re-rotate view
applying again

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

Changing x axis

Changing x axis
Changing x-axis

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

Changing y axis

y axis
Changing y axis

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

Changing z axis

Changing a index
Changing z index

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!

--

--

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!