Spring-animierter Button mit Zustandswechsel
Beschreibung
Diese View zeigt einen Button, der beim Tippen federnd skaliert und die Hintergrundfarbe wechselt. Der Effekt wird über eine gezielte Spring-Animation gesteuert und visualisiert den Zustandswechsel klar und reaktionsfreudig.
🔍 Zweck
- Interaktives Feedback beim Tippen auf Buttons
- Demonstration einer konfigurierbaren Spring-Animation
- Zustandsschalter mit klarer visueller Rückmeldung
- Prototyping von Mikrointeraktionen in UI-Elementen
- Verbesserung der Wahrnehmung von Aktionen in Formularen
🖥️ Betriebssystem
iOS
📄 Codebeispiel
import SwiftUI
@main
struct SpringButtonApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
public struct ContentView: View {
// Track whether the button is in "pressed" state
@State private var isPressed = false
public init() {}
public var body: some View {
VStack {
// The interactive button with spring animation and visual state
Button(action: togglePressed) {
Text("Press Me")
.padding()
// Background color reflects the current state
.background(isPressed ? Color.green : Color.blue)
.foregroundColor(.white)
.cornerRadius(10)
// Scale up when pressed for a playful microinteraction
.scaleEffect(isPressed ? 1.2 : 1.0)
// Provide an accessible label for assistive technologies
.accessibilityLabel(isPressed ? "Button pressed" : "Press button")
}
.buttonStyle(.plain) // Keep the custom styling intact
.padding()
}
}
// Toggle state using a tuned spring animation for snappy feedback
private func togglePressed() {
withAnimation(.spring(response: 0.3, dampingFraction: 0.5, blendDuration: 0)) {
isPressed.toggle()
}
}
}
// Modern Swift 5.10+ preview syntax
#Preview {
ContentView()
}