我想知道如何获得DragGesture
Velocity?
我知道这个公式是有效的,也知道如何手动获取它,但当我这样做的时候,苹果的回报就不在哪里了(至少有些时候是非常不同的(。
我有以下代码片段
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
。
根据拖动方式的不同,结果可能不同,也可能相同苹果提供了与.startLocation
和.endLocation
一样的速度属性,但不幸的是,我无法访问它(至少我不知道(所以我必须自己计算,理论上我的计算是正确的,但它们与苹果非常不同。那么这里的问题是什么呢?
这是从DragGesture.Value
中提取速度的另一种方法。它比解析另一个答案中建议的调试描述更健壮,但仍有可能中断。
import SwiftUI
extension DragGesture.Value {
/// The current drag velocity.
///
/// While the velocity value is contained in the value, it is not publicly available and we
/// have to apply tricks to retrieve it. The following code accesses the underlying value via
/// the `Mirror` type.
internal var velocity: CGSize {
let valueMirror = Mirror(reflecting: self)
for valueChild in valueMirror.children {
if valueChild.label == "velocity" {
let velocityMirror = Mirror(reflecting: valueChild.value)
for velocityChild in velocityMirror.children {
if velocityChild.label == "valuePerSecond" {
if let velocity = velocityChild.value as? CGSize {
return velocity
}
}
}
}
}
fatalError("Unable to retrieve velocity from (Self.self)")
}
}
就像这样:
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!)!)