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.
- You need @State variable to keep track of its flipped state.
- Attach
.rotation3DEffect()
with flag(@State var flipped: Bool) and change Angle accordingly. - In order to create animation effect, apply implicit animation to the view with
.animation(.default, value: flipped)
. - 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
- Create
@State var flipped
to keep track of your view’s flipped state. - Apply rotation3DEffect to your view
- Apply rotation3DEffect again to your target view (Re-rotate view)
- Apply Implicit Animation
That’s all!