SwiftUI Animations Implicit

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

Demo.swift

ContentView.swift

App.swift

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()
} }

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

Demo.swift

ContentView.swift

App.swift

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()
} }

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *