Skip to main content

Confetti Animation in SwiftUI

Published 2 min readMarkdown
Confetti Animation in SwiftUI

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.

About the author

  • 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 馃嚭馃嚫

No comments yet. Be the first to comment.

More from this blog