Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Implementing Dragging in SwiftUI
Written by Team Kodeco

Drag gestures are a powerful tool in enhancing interactivity in your apps, allowing users to intuitively move objects around the screen. In this cookbook entry, you’ll delve into the steps for implementing a drag gesture in SwiftUI.

In SwiftUI, you make use of the gesture modifier to handle drag gestures, feeding it an instance of DragGesture. DragGesture is an integral part of SwiftUI, designed to handle drag events.

Here’s a simple example where you attach a drag gesture to a circle shape, allowing it to be moved around the screen freely:

struct ContentView: View {
  @State private var circlePosition = CGPoint(x: 100, y: 100)

  var body: some View {
    Circle()
      .fill(Color.blue)
      .frame(width: 100, height: 100)
      .position(circlePosition)
      .gesture(
        DragGesture()
          .onChanged { gesture in
            self.circlePosition = gesture.location
          }
      )
  }
}

Your preview should look like this:

Use DragGesture with the gesture modifier to implement dragging.
Use DragGesture with the gesture modifier to implement dragging.

You begin by declaring a @State variable circlePosition, which tracks the circle’s current location on the screen. Following that, a Circle shape is created with a blue fill and dimensions set at 100x100. Its position is then set to the circlePosition.

The drag gesture is added to the circle using the gesture modifier, to which we pass a DragGesture instance. The closure given to the onChanged method of DragGesture updates the circlePosition to match the gesture’s ongoing location. Now, upon running this code, you’ll see a blue circle that you can interactively drag around the screen.

One point to remember is that, by default, DragGesture recognizes both horizontal and vertical drags. If you wish to restrict the gesture to a single direction, you can assign a non-zero value to the minimumDistance attribute of the gesture, like so:

DragGesture(minimumDistance: 0, coordinateSpace: .local)

In conclusion, incorporating a drag gesture in SwiftUI is straightforward and can significantly enhance your UI’s interactivity. Through the gesture modifier and the DragGesture type, you can craft immersive and engaging user interfaces with just a few lines of code.

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.