我正在尝试检测手指何时首次与SwiftUI中的视图进行接触。我可以使用UIKit Events非常轻松地做到这一点,但是无法在SwiftUI中解决这个问题。
我尝试过最小移动为0的DragGesture,但是直到您的手指移动它仍然不会改变。
TapGesture仅在您松开手指时起作用,而无论我将参数设置为什么,LongPressGesture都不会足够快地触发。
DragGesture(minimumDistance: 0, coordinateSpace: .local).onChanged({ _ in print("down")})
LongPressGesture(minimumDuration: 0.01, maximumDistance: 100).onEnded({_ in print("down")})
我想在手指与视图接触后立即检测到touchDown事件。苹果的默认手势对距离或时间有限制。
如果将这两个问题的代码组合在一起:
How to detect a tap gesture location in SwiftUI?
UITapGestureRecognizer - make it work on touch down, not touch up?
您可以制作这样的内容:
ZStack {
Text("Test")
TapView {
print("Tapped")
}
}
struct TapView: UIViewRepresentable {
var tappedCallback: (() -> Void)
func makeUIView(context: UIViewRepresentableContext<TapView>) -> TapView.UIViewType {
let v = UIView(frame: .zero)
let gesture = SingleTouchDownGestureRecognizer(target: context.coordinator,
action: #selector(Coordinator.tapped))
v.addGestureRecognizer(gesture)
return v
}
class Coordinator: NSObject {
var tappedCallback: (() -> Void)
init(tappedCallback: @escaping (() -> Void)) {
self.tappedCallback = tappedCallback
}
@objc func tapped(gesture:UITapGestureRecognizer) {
self.tappedCallback()
}
}
func makeCoordinator() -> TapView.Coordinator {
return Coordinator(tappedCallback:self.tappedCallback)
}
func updateUIView(_ uiView: UIView,
context: UIViewRepresentableContext<TapView>) {
}
}
class SingleTouchDownGestureRecognizer: UIGestureRecognizer {
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent) {
if self.state == .possible {
self.state = .recognized
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent) {
self.state = .failed
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent) {
self.state = .failed
}
}
我们肯定可以做出一些抽象,以便其用法更像其他SwiftUI手势,但这只是一个开始。希望苹果在某个时候能够对此提供支持。