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

余生颓废 提交于 2019-12-02 05:10:23

问题


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:

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?


回答1:


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.



来源:https://stackoverflow.com/questions/56943259/swiftui-error-in-dragging-logic-or-is-this-a-bug

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!