问题描述
我试图检测手指何时第一次接触 SwiftUI 中的视图.我可以使用 UIKit Events 轻松完成此操作,但无法在 SwiftUI 中解决此问题.
I'm trying to detect when a finger first makes contact with a view in SwiftUI. I could do this very easily with UIKit Events but can't figure this out in SwiftUI.
我尝试了最小移动为 0 的 DragGesture,但在您的手指移动之前它仍然不会改变.
I've tried a DragGesture with minimum movement of 0 but it still won't change until your finger moves.
TapGesture 仅在您抬起手指时才起作用,并且无论我将参数设置为什么,LongPressGesture 都不会足够快地触发.
TapGesture will only work when you lift your finger and LongPressGesture will not trigger fast enough no matter what I set the parameters to.
DragGesture(minimumDistance: 0, coordinateSpace: .local).onChanged({ _ in print("down")})
LongPressGesture(minimumDuration: 0.01, maximumDistance: 100).onEnded({_ in print("down")})
我想在手指与视图接触后立即检测到 touchDown 事件.Apple 的默认手势对距离或时间都有限制.
I want to detect a touchDown event as soon as a finger makes contact with a view. Apple's default gestures have restrictions to either distance or time.
更新:这不再是问题,因为 Apple 似乎更新了 DragGesture 的工作方式,或者我可能遇到了特定的上下文错误.
Update: This is not an issue anymore as Apple has seemed to update how DragGesture works or maybe I was experiencing a specific contextual bug.
推荐答案
如果将这两个问题的代码结合起来:
If you combine the code from these two questions:
UITapGestureRecognizer - 让它在触地时工作,而不是触地?
你可以做这样的事情:
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 手势,但这是一个开始.希望 Apple 在某个时候能够对此提供支持.
There's definitely some abstractions we can make so that the usage is more like the other SwiftUI Gestures, but this is a start. Hopefully Apple builds in support for this at some point.
这篇关于您如何检测没有移动或持续时间的 SwiftUI touchDown 事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!