Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Animate Binding Values in SwiftUI
Written by Team Kodeco

Animating bindings serves as one of the most potent tools at your disposal when designing with SwiftUI. With it, you can breathe life into your user interfaces by designing them to dynamically respond to changing data. In this chapter, you will learn how to harness SwiftUI’s built-in animation capabilities to craft graceful animations for your binding values.

In SwiftUI, a typical method to animate bound values is by placing the animation modifier directly on a data binding. This results in the corresponding UI control animating whenever the bound value changes.

Let’s explore this concept with an example involving a Picker UI control:

struct ContentView: View {
  @State private var selection = 0

  var body: some View {
    VStack {
      Text("Your selection is: \(selection)")
        .font(.title)

      Picker("Choose a number", selection: $selection.animation()) {
        ForEach(0..<10) {
          Text("\($0)")
        }
      }
      .pickerStyle(.wheel)
      .frame(width: 100, height: 200)
    }
  }
}

Your preview should look like this:

To animate a control, add an animation modifer to its data binding.
To animate a control, add an animation modifer to its data binding.

In this scenario, you utilize a Picker view that is bound to the selection state variable. The .animation() modifier is applied directly to the binding. Therefore, each time the selection value is modified through the Picker, the Picker animates the change.

The animation seamlessly transitions between the selected numbers, offering a visual representation of the selection changing. It enhances user interaction by providing smooth visual feedback.

Please note that the animation modifier is used without parameters in this example, hence SwiftUI uses the default animation. You are free to customize this by providing parameters as per your requirements.

In conclusion, animating binding values with SwiftUI allows you to build vibrant, interactive user interfaces. Be it numbers, colors, positions or UI controls like Picker, SwiftUI makes it convenient to create visually appealing, smooth animations that bolster the aesthetic quotient of your application. Harness the power of the animation modifier on data bindings and witness your app come alive with dynamic transitions.

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.