Animierter Zähler mit Übergangseffekt
Beschreibung
Diese View zeigt einen Zähler, der beim Erhöhen mit einem animierten Übergang zwischen den Zahlen wechselt. Die Ein- und Ausblendung wird durch eine Kombination von Bewegung und Transparenz umgesetzt, was die Änderung visuell hervorhebt.
🔍 Zweck
- Darstellung von dynamischen Werten mit ansprechender Animation
- Einsatz in Gamification-Elementen wie Punkteständen
- Verbesserung der Nutzerwahrnehmung bei Statusänderungen
- Demonstration von asymmetrischen Transitionen in SwiftUI
- Prototyping für interaktive Dashboards oder Zähleranzeigen
🖥️ Betriebssystem
iOS
📄 Codebeispiel
import SwiftUI
@main
struct AnimatedCounterApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
public struct ContentView: View {
// Track the current counter value
@State private var counter = 0
public init() {}
public var body: some View {
VStack {
ZStack {
// Display the counter value with custom transition
Text("\(counter)")
.font(.system(size: 80, weight: .bold))
.transition(.asymmetric(
// Insert animation: slide in from bottom with fade
insertion: .move(edge: .bottom).combined(with: .opacity),
// Removal animation: slide out to top with fade
removal: .move(edge: .top).combined(with: .opacity)
))
.id(counter) // Force new identity so transition is triggered
}
// Fixed height ensures smooth animation regardless of value
.frame(height: 100)
// Button to increment the counter
Button(action: incrementCounter) {
Text("Increase")
.font(.title)
.padding()
.background(Color.green)
.foregroundColor(.white)
.clipShape(Capsule())
}
}
.padding()
}
// Increment counter with spring animation for natural motion
private func incrementCounter() {
withAnimation(.spring(response: 0.4, dampingFraction: 0.6, blendDuration: 0.2)) {
counter += 1
}
}
}
// Modern Swift 5.10+ preview syntax
#Preview {
ContentView()
}