SwiftUI Animations Implicit
SwiftUI Animations: Implicit
Attach an animation to a view so changes to a bound value animate automatically.
Syntax
Attach animation: .animation(.easeInOut, value: state).
Any modifier that depends on state will animate when state changes.
Tap to Grow (Implicit)
Attaching .animation(..., value: on) to the circle animates its size and color whenever on toggles.
Example
import SwiftUI
struct ImplicitAnimDemo: View {
@State private var on = false
var body: some View {
VStack(spacing: 12) {
Circle()
.fill(on ? .green : .gray)
.frame(width: on ? 120 : 60, height: on ? 120 : 60)
.animation(.spring(), value: on)
Button(on ? "Reset" : "Grow") { on.toggle() }
}
.padding()
}
}
import SwiftUI
struct ContentView: View {
var body: some View { ImplicitAnimDemo() }
}
import SwiftUI
@main
struct MyApp: App {
var body: some Scene {
WindowGroup { ContentView() }
}
}
In the example above, the circle's size and color animate when the on state changes.
Implicitly Animate Multiple Modifiers
Attach a single .animation and change several properties; scale, opacity, and color animate when the state toggles.
Example
import SwiftUI
struct ImplicitMultiDemo: 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.25 : 1.0)
.opacity(on ? 1 : 0.6)
.animation(.easeInOut(duration: 0.6), value: on)
Button(on ? "Reset" : "Animate") { on.toggle() }
}
.padding()
}
}
import SwiftUI
struct ContentView: View {
var body: some View { ImplicitMultiDemo() }
}
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.