Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Animate a View's Position in SwiftUI
Written by Team Kodeco

Animating a view’s position can be a powerful tool for enhancing user experience and drawing attention to important elements on your screen. SwiftUI makes it easy to add simple, yet elegant animations to your app.

To animate a view’s position in SwiftUI, you’ll need to use the offset modifier in combination with an animation modifier. Here’s a simple code example that animates a view’s position:

struct ContentView: View {
  @State var offset = CGSize(width: 0, height: 0)

  var body: some View {
    Image(systemName: "arrow.up")
      .font(.largeTitle)
      .offset(offset)
      .animation(.spring(), value: offset)
      .gesture(
        DragGesture()
          .onChanged { value in
            offset = value.translation
          }
          .onEnded { _ in
            withAnimation {
              offset = .zero
            }
          }
      )
  }
}

Your preview should look like this:

Animate dragging a view with the offset modifier.
Animate dragging a view with the offset modifier.

In this code example, you’re animating an image of an upward arrow. To start, you create a state variable called offset that represents the position of the arrow. You then set the offset of the image to be equal to your state variable using the offset modifier.

Next, you add an animation modifier to specify the type of animation you want to use and the value to track for changes. In this case, you’re using a spring animation and tracking the offset property.

Finally, a gesture modifier is attached to the view to respond to the user’s dragging actions. The DragGesture tracks the user’s movement, updating the arrow’s offset to match the translation (the change in position from the start of the gesture to the current location) of the gesture. When the user lifts their finger, the withAnimation function is used to animate the arrow back to its original position to create a bouncing effect.

With just a few lines of code, you’ve added a simple and elegant animation that enhances the user experience. By experimenting with different animation types and gestures, you can create engaging and interactive user interfaces that users will love.

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.