This post is about creating a confetti animation in SwiftUI with a customizable duration. I learned the technique from this Patreon tutorial.
In the original animation, the confetti pieces would change color while falling, which I considered a bug. I’ve since fixed it. Another optimization I considered was adding a fade-out effect to make the disappearance of the confetti smoother, but the result wasn’t satisfactory, so I have not included that change.
Let’s break down how to build this.
Step 1: Animate a Single Piece of Confetti
First, we’ll create the animation for a single piece of confetti. The code and the result are below:
This line of code is the key to fixing the color-changing issue:
@State private var color: Color = [.orange, .green, .blue, .red, .yellow].randomElement() ?? .green
The color used to change because the original code would assign a new random color during the animation process. By using @State to store the color, we ensure its value is preserved for the view’s lifetime, preventing the color from changing unexpectedly.
Step 2: Create the Confetti Container
Next, we’ll create a container to hold 50 confetti pieces and manage their positioning.