Skip to main content

Command Palette

Search for a command to run...

Confetti Animation in SwiftUI

Published
โ€ข2 min read
Confetti Animation in SwiftUI
M

I am a Software Engineer working on open source and enterprise mobile SDKs for iOS and MacOS developers written in Swift. From ๐Ÿ‡ฉ๐Ÿ‡ช and happily living in ๐Ÿ‡บ๐Ÿ‡ธ

The open-source Swift package ConfettiSwiftUI lets you to create and customize confetti animations built with SwiftUI.

Default Animation

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)

makeItRain.gif

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.

More from this blog

Dev blog post potpourri by senior software engineer Marco Eidinger

149 posts

Hello ๐Ÿ‘‹๐Ÿป , I am a Software Engineer working on open source and enterprise mobile SDKs for iOS and MacOS developers written in Swift. From ๐Ÿ‡ฉ๐Ÿ‡ช and happily living in ๐Ÿ‡บ๐Ÿ‡ธ