SwiftUI on macOS - handle single-click and double-click at the same time

人盡茶涼 提交于 2021-01-27 18:10:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!