SwiftUI:拖动逻辑出错还是这是一个错误? [英] SwiftUI: Error in dragging logic or is this a bug?
问题描述
SwiftUI 处于测试阶段,所以这可能是一个错误,但我在其他 YouTube 视频中看到过类似的东西,所以也许不是,测试非常简单.我正在创建一个可以水平拖动的圆圈.
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
这会导致行为:
据我所知,DragGesture
onChanged
回调中的 value.location
值不应该像这样在数字之间波动.查看日志,数字到处都是.我错过了什么吗?
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?
推荐答案
DragGesture
的默认 CoordinateSpace
是 .local
,这是Circle
内的坐标空间.当您移动 Circle
时会发生什么?由于您的手指没有移动,您的手指在 Circle
的几何图形中的位置突然发生了变化,从而导致 Circle
再次移动.重复恶心.
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.
尝试使用CoordinateSpace.global
:
DragGesture(minimumDistance: 10, coordinateSpace: .global)
您可能还想使用 value.translation
而不是 value.location
来避免手指向下时的初始跳跃.
You'll probably also want to use value.translation
instead of value.location
to avoid the initial jump when you put your finger down.
这篇关于SwiftUI:拖动逻辑出错还是这是一个错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!