SwiftUI Animations Explicit
SwiftUI Animations: Explicit
Wrap state changes in withAnimation to control when and how to animate.
Syntax
withAnimation: withAnimation(.easeInOut) { state.toggle() }. All view modifier changes inside the block animate together.
Rotate on Tap
Tapping the button triggers withAnimation to rotate the icon by 180 degrees.
Example
import SwiftUI
struct ExplicitAnimDemo: View {
@State private var angle = 0.0
var body: some View {
VStack(spacing: 12) {
Image(systemName: "arrow.2.circlepath").rotationEffect(.degrees(angle))
Button("Rotate") { withAnimation(.easeInOut) { angle += 180 } }
}
}
}
import SwiftUI
struct ContentView: View {
var body: some View { ExplicitAnimDemo() }
}
import SwiftUI
@main
struct MyApp: App {
var body: some Scene {
WindowGroup { ContentView() }
}
}
In the example above, the arrow icon rotates 180 degrees when the angle state changes.
Animate Multiple Properties
Use withAnimation to animate rotation, scale, color, and opacity in a single state change.
Example
import SwiftUI
struct ExplicitMultiDemo: View {
@State private var on = false
var body: some View {
VStack(spacing: 16) {
Image(systemName: "star.fill")
.font(.system(size: 48))
.foregroundStyle(on ? .yellow : .gray)
.scaleEffect(on ? 1.3 : 1.0)
.rotationEffect(.degrees(on ? 180 : 0))
.opacity(on ? 1 : 0.6)
Button(on ? "Reset" : "Animate") {
withAnimation(.easeInOut(duration: 0.6)) { on.toggle() }
}
}
}
}
import SwiftUI
struct ContentView: View {
var body: some View { ExplicitMultiDemo() }
}
import SwiftUI
@main
struct MyApp: App {
var body: some Scene {
WindowGroup { ContentView() }
}
}
In the example above, the star's size, color, and opacity animate when the on state changes.