跳转至
Structure

DragGesture

A dragging motion that invokes an action as the drag-event sequence changes.

Declaration

struct DragGesture : Gesture

Overview

To recognize a drag gesture on a view, create and configure the gesture, and then add it to the view using the gesture(_:including:) modifier.

Add a drag gesture to a Circle and change its color while the user performs the drag gesture:

struct DragGestureView: View {
    @State private var location: CGPoint = CGPoint(x: 50, y: 50);
    @State var isDragging = false

    var simpleDrag: some Gesture {
        DragGesture()
            .onChanged { value in
                self.location = value.location
                self.isDragging = true

            }
            .onEnded {\_ in self.isDragging = false}
    }

    var body: some View {
        Circle()
            .fill(self.isDragging ? Color.red : Color.yellow)
            .frame(width: 100, height: 100)
            .position(location)
            .gesture(simpleDrag)
    }
}
A gif displaying a view contining a drag gesture and a circle, connected by state variables; when  dragged, the circle turns from yellow to red.

Availability

iOS 13.0+

macOS 10.15+

watchOS 6.0+

Topics


Structure

Value The attributes of a drag gesture.


Initializer

init(minimumDistance:coordinateSpace:) Creates a dragging gesture with the minimum dragging distance before the gesture succeeds and the coordinate space of the gesture's location.


Type Alias

Body The type of gesture representing the body of Self.


Instance Property

coordinateSpace The coordinate space in which to receive location values.

minimumDistance The minimum dragging distance before the gesture succeeds.