问题
Consider this view in SwiftUI:
struct MyView: View {
var body: some View {
Rectangle()
.fill(Color.blue)
.frame(width: 200, height: 200)
.onTapGesture {
print("single clicked")
}
}
}
Now we're handling single-click. Say you wanna handle double-click too, but with a separate callback.
You have 2 options:
- Add double click handler after single click - this doesn't work at all
- Add double click handler before single click handler, this kinda works:
struct MyView: View {
var body: some View {
Rectangle()
.fill(Color.blue)
.frame(width: 200, height: 200)
.onTapGesture(count: 2) {
print("double clicked")
}
.onTapGesture {
print("single clicked")
}
}
}
Double-click handler is called properly, but single-click handler is called after a delay of about 250ms.
Any ideas how to resolve this?
回答1:
Here is possible approach (tested with Xcode 11.2 / macOS 10.15)
struct MyView: View {
var body: some View {
Rectangle()
.fill(Color.blue)
.frame(width: 200, height: 200)
.gesture(TapGesture(count: 2).onEnded {
print("double clicked")
})
.simultaneousGesture(TapGesture().onEnded {
print("single clicked")
})
}
}
来源:https://stackoverflow.com/questions/59992089/swiftui-on-macos-handle-single-click-and-double-click-at-the-same-time