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

Demo.swift

ContentView.swift

App.swift

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

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

Demo.swift

ContentView.swift

App.swift

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

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

Demo.swift

ContentView.swift

App.swift

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

Comments

Leave a Reply

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