SwiftUI iOS - 添加双击导致延迟后调用单击 [英] SwiftUI iOS - Adding Double tap cause Single tap called after a delay
问题描述
我想在下面的 Capsule
上识别单击和双击.此代码工作正常:
I want to recognize Single tap and Double tap on the Capsule
below. This code works fine :
Capsule()
.frame(width: 100, height: 42)
.onTapGesture(count: 1) {
print("Single Tap recognized instantly")
}
但是当我将 .onTapGesture(count: 2)
添加到它时在 0.25 毫秒后调用一次.
But When I'm adding the .onTapGesture(count: 2)
to it Single tap called after 0.25ms.
Capsule()
.frame(width: 100, height: 42)
.onTapGesture(count: 2) {
print("Double tap recognized instantly")
}
.onTapGesture(count: 1) {
print("Single Tap recognized after 0.25ms")
}
我该如何解决这个问题?
How can I fix this?
推荐答案
只是想说明一点:当您的目标是专门检测两者时,您不能将单个点击手势与双击手势一起识别(即系统应该区分单击和双击而没有延迟)因为理论上单击总是会导致双击.这意味着您总是必须等待一段时间(在您的情况下似乎是 0.25 毫秒)才能排除用户打算双击.
Just to make one thing clear: You cannot have a single tap-gesture that should be recognized together with a double tap gesture when your goal is to detect both exclusively (i.e. the system should differentiate between a single tap and a double tap with no delay) since a single tap could theoretically always lead to a double tap. This means you always have to wait a certain period (of 0.25 ms as it seems in your case) to rule out the user intended to double-tap.
但是,当您的目标是将单个点击手势与双击手势一起(换句话说,同时)使用时,这现在完全可行.
However, when your goal is to have a single tap-gesture together (in other words simultaneously) with the double-tap gesture, this is now completely feasible.
手势,就像 SwiftUI 中的许多东西一样,是一个 protocol
并且自定义手势可以通过多种方式构建,例如视图的 body
.在您的情况下,我们想要一个与单击手势同时运行的双击手势.最简单的方法是,声明一个具有不透明返回类型(some Gesture
)的计算属性,并在该属性中描述您的手势:
A gesture is, like so many things in SwiftUI a protocol
and custom gestures can be built in a lot of ways like the body
of a view. In your case, we want a double tap-gesture that runs simultaneously with a single tap gesture. The simplest way to this, you declare a computed property with an opaque return type (some Gesture
) and describe your gesture in that property:
var tapGesture: some Gesture {
TapGesture(count: 2)
.onEnded {
print("Double tap")
}
.simultaneously(with: TapGesture(count: 1)
.onEnded {
print("Single Tap")
})
}
您可以简单地将此手势添加到您想要的任何视图,就像您对任何其他手势执行相同的操作一样:
You can simply add this gesture to whatever view you desire, just like you would do the same thing with any other gesture:
Capsule()
.gesture(tapGesture)
这篇关于SwiftUI iOS - 添加双击导致延迟后调用单击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!