Farbwechselndes Rechteck mit Tap-Geste
Beschreibung
HierDiese wirdView zeigt ein Quadratfarbiges gezeichnet. Beim Starten wirdRechteck, das Rechteckbei 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
rotSwiftUI
🖥️ einenBetriebssystem
iOS
📄 das Quadrat, wechselt die Farbe nach Grün. Bei jedem weiteren Tap wird die nächste Farbe aus dem Array colors genommen. Wird Lila angezeigt und es gibt einen erneuten Tap, wird wieder rot angezeigt.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()
}