Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI: Error in dragging logic or is this a bug?

SwiftUI is in beta, so maybe this is a bug, but I've seen something like this working in others YouTube videos so perhaps it's not, the test is pretty simple. I'm creating a circle I can drag around on horizontally.

import SwiftUI

struct ContentView : View {
    @State private var location = CGPoint.zero
    var body: some View {
        return Circle()
            .fill(Color.blue)
            .frame(width: 300, height: 300)
            .gesture(
                DragGesture(minimumDistance: 10)
                    .onChanged { value in
                        print("value.location")
                        print(value.location)
                        self.location = CGPoint(
                            x: value.location.x,
                            y: 0)
                }
        )
            .offset(x: self.location.x, y: self.location.y)
    }
}

#if DEBUG
struct ContentView_Previews : PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
#endif

This results in the behavior:

iphone capture

As far as I can tell, the value.location value in the DragGesture onChanged callback shouldn't be fluctuating between numbers like this. Looking at the logs the numbers are all over the place. Am I missing something?

like image 565
adammenges Avatar asked Dec 01 '22 09:12

adammenges


1 Answers

DragGesture's default CoordinateSpace is .local, which is the coordinate space inside your Circle. What happens when you move the Circle? Since your finger doesn't move, the location of your finger in the Circle's geometry suddenly changes, which causes the Circle to move again. Repeat ad nauseum.

Try using CoordinateSpace.global:

DragGesture(minimumDistance: 10, coordinateSpace: .global)

You'll probably also want to use value.translation instead of value.location to avoid the initial jump when you put your finger down.

like image 171
rob mayoff Avatar answered Dec 26 '22 00:12

rob mayoff