4

我想知道如何获得DragGesture速度?

我了解该公式的工作原理以及如何手动获取它,但是当我这样做时,它不是 Apple 返回的地方(至少有时它非常不同)。

我有以下代码片段

struct SecondView: View {
    @State private var lastValue: DragGesture.Value?

    private var dragGesture: some Gesture {
        DragGesture()
             .onChanged { (value) in
                   self.lastValue = value
             }
             .onEnded { (value) in
                   if lastValue = self.lastValue {
                         let timeDiff = value.time.timeIntervalSince(lastValue.time)
                         print("Actual \(value)")   // <- A
                         print("Calculated: \((value.translation.height - lastValue.translation.height)/timeDiff)") // <- B
                   }
             }

     var body: some View {
          Color.red
              .frame(width: 50, height: 50)
              .gesture(self.dragGesture)
     }
}

从上面:

A将输出类似Value(time: 2001-01-02 16:37:14 +0000, location: (250.0, -111.0), startLocation: (249.66665649414062, 71.0), velocity: SwiftUI._Velocity<__C.CGSize>(valuePerSecond: (163.23212105439427, 71.91841849340494)))

B将输出类似Calculated: 287.6736739736197

请注意,A我正在查看第二个值,valuePerSecond其中y velocity.

根据您拖动的方式,结果将不同或相同。Apple 提供了速度作为属性.startLocation.endLocation但不幸的是我无法访问它(至少我不知道)所以我必须自己计算它,理论上我的计算是正确的,但它们与 Apple 有很大不同。那么这里的问题是什么?

4

1 回答 1

0

像这样:

let sss = "\(value)"
//Intercept string
let start = sss.range(of: "valuePerSecond: (")
let end = sss.range(of: ")))")
let arr = String(sss[(start!.upperBound)..<(end!.lowerBound)]).components(separatedBy: ",")
print(Double(arr.first!)!)
于 2020-09-08T07:32:56.050 回答