SwiftUI Animations & Transitions
SwiftUI Animations & Transitions
Animate view changes with withAnimation and apply .transition for insert/remove effects.
Implicit Animations
Attach an animation to a state-driven view modifier so changes animate automatically.
Syntax:
.animation(.easeInOut, value: state).animation(.spring(), value: state)
Example
import SwiftUI
struct ImplicitDemo: View {
@State private var on = false
var body: some View {
Circle()
.fill(on ? .green : .gray)
.frame(width: on ? 120 : 60, height: on ? 120 : 60)
.animation(.spring(), value: on)
.onTapGesture { on.toggle() }
}
}
import SwiftUI
struct ContentView: View {
var body: some View { ImplicitDemo() }
}
import SwiftUI
@main
struct MyApp: App {
var body: some Scene {
WindowGroup { ContentView() }
}
}
This example animates color and size whenever the boolean state changes, using a spring animation.
Explicit Animations
Wrap state changes in withAnimation to control when and how to animate.
Syntax: withAnimation(.easeInOut) { state.toggle() }
Example
import SwiftUI
struct ExplicitDemo: 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 { ExplicitDemo() }
}
import SwiftUI
@main
struct MyApp: App {
var body: some Scene {
WindowGroup { ContentView() }
}
}
This example explicitly animates rotation when the button is pressed.
Transitions
Animate views as they insert/remove with .transition and .animation.
Syntax:
.transition(.slide).transition(.opacity.combined(with: .scale))
Example
import SwiftUI
struct TransitionDemo: View {
@State private var show = false
var body: some View {
VStack(spacing: 12) {
Button(show ? "Hide" : "Show") {
withAnimation(.easeInOut) { show.toggle() }
}
if show {
Text("Hello")
.padding(12)
.background(.blue.opacity(0.1))
.cornerRadius(8)
.transition(.opacity.combined(with: .scale))
}
}
}
}
import SwiftUI
struct ContentView: View {
var body: some View { TransitionDemo() }
}
import SwiftUI
@main
struct MyApp: App {
var body: some Scene {
WindowGroup { ContentView() }
}
}
This example fades and scales a view on insert/remove using a combined transition with an explicit animation.
Tip: Prefer implicit animations for simple state changes; use explicit withAnimation when you need control.