在 SwiftUI 中,许多手势支持类似 onPressingChanged 的闭包回调,用于在手势状态发生变化时提供信息。这些回调可以让开发者根据手势的不同阶段执行特定的逻辑。以下是一些常见手势和它们的相关闭包回调:
1、TapGesture
用于检测轻触手势。
使用闭包:
onEnded: 当手势完成(手指抬起)时调用。
示例:
Text("Tap me!")
.gesture(
TapGesture()
.onEnded {
print("Tapped!")
}
)

2、DragGesture
用于检测拖动手势。
使用闭包:
onChanged: 在拖动过程中每帧调用,传递当前位置的 DragGesture.Value。
onEnded: 在拖动结束(手指抬起)时调用,传递最终位置的 DragGesture.Value。示例:
Rectangle()
.gesture(
DragGesture()
.onChanged { value in
print("Dragging at: \(value.location)")
}
.onEnded { value in
print("Drag ended at: \(value.location)")
}
)

3、LongPressGesture
用于检测长按手势。
使用闭包:
onPressingChanged: 长按状态改变时调用,传递一个布尔值。
onEnded: 长按完成后调用。
示例:
Text("Long press me!")
.onLongPressGesture(minimumDuration: 2) {
print("Long press ended!")
} onPressingChanged: { inProgress in
print("Long press in progress: \(inProgress)")
}

4、MagnificationGesture
用于检测捏合缩放手势。
使用闭包:
onChanged: 捏合过程中每帧调用,传递当前的缩放值。
onEnded: 捏合结束时调用,传递最终的缩放值。
示例:
Circle()
.gesture(
MagnificationGesture()
.onChanged { scale in
print("Magnifying: \(scale)")
}
.onEnded { scale in
print("Magnification ended with scale: \(scale)")
}
)

5、RotationGesture
用于检测旋转手势。
使用闭包:
onChanged: 旋转过程中每帧调用,传递当前旋转角度。
onEnded: 旋转结束时调用,传递最终旋转角度。
示例:
Image(systemName: "arrow.triangle.2.circlepath")
.gesture(
RotationGesture()
.onChanged { angle in
print("Rotating: \(angle)")
}
.onEnded { angle in
print("Rotation ended with angle: \(angle)")
}
)

6、SimultaneousGesture 和 ExclusiveGesture
这些组合手势不直接提供状态变化的闭包,但可以嵌套其他手势来结合它们的行为。
示例:
Text("Combined Gestures")
.gesture(
TapGesture().simultaneously(with: LongPressGesture())
.onEnded { _ in
print("Tap or Long Press ended!")
}
)

总结
常见的手势和回调方式:
1)TapGesture:无状态回调,结束回调onEnded。
2)DragGesture:状态回调onChanged,结束回调onEnded。
3)LongPressGesture:状态回调onPressingChanged,结束回调onEnded。
4)MagnificationGesture:状态回调onChanged,结束回调onEnded。
5)RotationGesture:状态回调onChanged,结束回调onEnded。
