import SwiftUI
struct ContentView: View {
@State private var isRed = true
var body: some View {
VStack(spacing: 20) {
Rectangle()
.frame(width: 150, height: 150)
.foregroundColor(isRed ? .red : .blue)
Button("Toggle Color") {
withAnimation {
isRed.toggle()
}
}
}
.padding()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}We use withAnimation to wrap the state change isRed.toggle(). This tells SwiftUI to animate any view changes caused by this state update. The Rectangle changes its foregroundColor based on isRed. When toggled inside withAnimation, the color smoothly transitions between red and blue.
This is a simple way to add animation to state changes without manually defining animation modifiers.