【问题标题】:SwiftUI: Error in dragging logic or is this a bug?SwiftUI:拖动逻辑错误还是这是一个错误?
【发布时间】:2019-11-18 11:03:49
【问题描述】:

SwiftUI 处于测试阶段,所以这可能是一个错误,但我在其他 YouTube 视频中看到过类似的东西,所以也许不是,测试非常简单。我正在创建一个可以水平拖动的圆圈。

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 值不应在这样的数字之间波动。看着日志,数字到处都是。我错过了什么吗?

【问题讨论】:

  • minimumDistance 设置为0 时会发生什么?
  • @LinusGeffarth 大致相同,尽管跳跃可能没有那么大:imgur.com/a/qp8l0dl
  • 你在ContentView(或类似的,你叫TestView())中的代码是什么?
  • TestView 是我的ContentView。我将在SceneDelegate 中作为根视图加载的视图切换到我正在使用的任何测试组件。不应该有什么不同,因为如果我将此代码复制粘贴到一个全新的 SwiftUI 项目中,我会看到同样的情况。事后看来,我应该这样做,所以我没有将人们与 TestView 混淆。
  • 我编辑了上面的代码。做了一个全新的项目,只是将Text("Hello world") 改写为现在的内容,只是为了让它更干净。结果相同。感谢您呼吁消除红鲱鱼。

标签: ios swift iphone ios-simulator swiftui


【解决方案1】:

DragGesture 的默认CoordinateSpace.local,即Circle 内部的坐标空间。当您移动Circle 时会发生什么?由于你的手指没有移动,你的手指在Circle 的几何图形中的位置突然改变,这导致Circle 再次移动。重复令人作呕。

尝试使用CoordinateSpace.global

DragGesture(minimumDistance: 10, coordinateSpace: .global)

您可能还想使用value.translation 而不是value.location 来避免手指向下时的初始跳跃。

【讨论】:

    猜你喜欢
    • 2021-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-26
    • 2012-01-29
    • 1970-01-01
    • 2012-10-14
    相关资源
    最近更新 更多