Skip to main content

Farbwechselndes Rechteck mit Tap-Geste

Beschreibung

Diese View zeigt ein farbiges Rechteck, das bei jedem Tippen seine Farbe wechselt. Die Übergänge zwischen den Farben werden mit einer sanften Ease-In-Out-Animation dargestellt.

🔍 Zweck

  • Demonstration von Animationen bei Zustandsänderungen
  • Erstellung interaktiver UI-Elemente mit Farbwechsel
  • Prototyping von Farbschemata oder Themes
  • Visualisierung von Klick- oder Auswahlaktionen
  • Lernbeispiel für Tap-Gesten in SwiftUI

🖥️ Betriebssystem

iOS

📄 Codebeispiel

import SwiftUI

@main
struct ColorChangingRectangleApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

public struct ContentView: View {
    // Track the current color index
    @State private var colorIndex = 0
    
    // Define a palette of colors to cycle through
    let colors: [Color] = [.red, .green, .blue, .orange, .purple]

    public init() {}

    public var body: some View {
        Rectangle()
            // Fill rectangle with the current color
            .fill(colors[colorIndex])
            .frame(width: 200, height: 200)
            // Tap gesture cycles to the next color
            .onTapGesture {
                colorIndex = (colorIndex + 1) % colors.count
            }
            // Animate the color transition for smooth effect
            .animation(.easeInOut(duration: 0.5), value: colorIndex)
            .padding()
    }
}

// Modern Swift 5.10+ preview syntax
#Preview {
    ContentView()
}