The open-source Swift package ConfettiSwiftUI
lets you to create and customize confetti animations built with SwiftUI.
I am impressed by its ease of use and rich customization options.
You need to write three lines of code to apply a beautiful confetti animation for your SwiftUI view.
import ConfettiSwiftUI // 1. import package
import SwiftUI
struct ContentView: View {
@State private var counter: Int = 0 // 2. define state variable
var body: some View {
Button("π") {
counter += 1
}
.confettiCannon(counter: $counter) // 3. done => magic :)
}
}
You can trigger a new animation by changing an integer-based state variable. The ViewBuilder function .confettiCannon
, an extension on View
, does the rest.
A variety of function parameters allows you to configure the confetti animation, e.g. you can change the
- amount of confetti
- shapes and text
- colors applied to the default shapes
- radius and angles of the explosion
- explosion repetition
- duration between explosion repetitions
Probably my favorite option is to use emojis as text.
.confettiCannon(counter: $counter, num:1, confettis: [.text("π΅"), .text("πΆ"), .text("π·"), .text("π΄")], confettiSize: 30, repetitions: 50, repetitionInterval: 0.1)
ConfettiSwiftUI
is a lovely, cross-platform utility package with no additional dependencies.
platforms: [
.iOS(.v14),
.macOS(.v11),
.tvOS(.v14),
.watchOS(.v7)
]
I recommend to explore the Demo App to make your desired animation or get inspired by one of the many examples.