Marco Eidinger
Swifty Tech by Marco Eidinger

Swifty Tech by Marco Eidinger

Confetti Animation in SwiftUI

Photo by Hugo Ruiz on Unsplash

Confetti Animation in SwiftUI

Marco Eidinger's photo
Marco Eidinger
Β·May 3, 2022Β·

2 min read

Subscribe to my newsletter and never miss my upcoming articles

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.

Did you find this article valuable?

Support Marco Eidinger by becoming a sponsor. Any amount is appreciated!

See recent sponsors |Β Learn more about Hashnode Sponsors
Β 
Share this