Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Optimizing Animations in SwiftUI
Written by Team Kodeco

Animations add a layer of dynamism and interactivity to SwiftUI apps. However, uncontrolled animations can impact the app’s performance. SwiftUI provides two primary ways of controlling animations for performance optimization:

  • Use the animation modifier for implicit animations.
  • Use withAnimation for explicit animations.

Implicit Animations With the animation Modifier

Implicit animations are the default in SwiftUI. When a state variable changes, SwiftUI automatically applies animations to all dependent views. The animation modifier allows you to control the animation type. For instance:

struct ContentView: View {
  @State private var scale = 1.0

  var body: some View {
    Circle()
      .fill(Color.blue)
      .frame(width: 100 * scale, height: 100 * scale)
      .scaleEffect(scale)
      .onTapGesture {
        scale += 0.5
      }
      .animation(.spring(), value: scale) // implicit animation
  }
}

Here’s what your preview should look like:

A SwiftUI View with an implicit animation.
A SwiftUI View with an implicit animation.

Here, .animation(.spring(), value: scale) modifies the Circle to animate using a spring animation whenever scale changes.

Explicit animations with withAnimation

Explicit animations give more control over what changes should animate. This is achieved using the withAnimation function, specifying exactly what should animate:

struct ContentView: View {
  @State private var scale = 1.0

  var body: some View {
    Circle()
      .fill(Color.blue)
      .frame(width: 100 * scale, height: 100 * scale)
      .scaleEffect(scale)
      .onTapGesture {
        withAnimation(.spring()) { // explicit animation
          scale += 0.5
        }
      }
  }
}

A SwiftUI View with an explicit animation.
A SwiftUI View with an explicit animation.

In this example, the withAnimation(.spring()) block encloses the state change, making the scale change explicitly animated.

The choice between explicit and implicit animations depends on your needs. Explicit animations are ideal when specific state changes need animation, while implicit animations apply universally to all state-dependent views and are simpler to use.

Finally, it’s essential to balance animations and app performance. Too many animations can impact the responsiveness of your app. Use animations judiciously for an optimal user experience. It’s a good idea to regularly profile your app using Instruments to ensure that your animations aren’t impacting your app’s performance. By following these practices, you can create engaging and performant animations in your SwiftUI app.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.