SwiftUI Animations Explicit

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

Demo.swift

ContentView.swift

App.swift

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

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

Demo.swift

ContentView.swift

App.swift

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

Comments

Leave a Reply

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