1

DragGesture in SwiftUI gives me location and currentLocation, but I'm at a loss to understand what the numbers mean except in relation to each other. How can I use those numbers to figure out if I'm dragging around in the top half of my view or my bottom half?

Rectangle()
  .frame(500, 500)
  .gesture(
      DragGesture()
      .onEnded { data in
         // if I mostly drew in the top half of the rectangle, color the top half
         // otherwise color the bottom half
       }

Vlad the Impala
  • 15,572
  • 16
  • 81
  • 124

1 Answers1

2

By default DragGesture is created for local namespace, so you get location as offset from initial position

/// Creates a dragging gesture with the minimum dragging distance before the
/// gesture succeeds and the coordinate space of the gesture's location.
///
/// - Parameters:
///   - minimumDistance: The minimum dragging distance for the gesture to
///     succeed.
///   - coordinateSpace: The coordinate space of the dragging gesture's
///     location.
public init(minimumDistance: CGFloat = 10, coordinateSpace: CoordinateSpace = .local)

but you can also create DragGesture with global namespace

Rectangle()
  .frame(500, 500)
  .gesture(
      DragGesture(coordinateSpace: .global))

and location in window coordinates. As well you can declare custom coordinate space in some of superview and have drag gesture location in that space

{
  // ...
  Rectangle()
    .frame(500, 500)
    .gesture(
       DragGesture(coordinateSpace: .named("owner")))
  // ...
}
.coordinateSpace(name: "owner")

See the following for example https://stackoverflow.com/a/60495440/12299030

Asperi
  • 228,894
  • 20
  • 464
  • 690