如何在onTapGesture中获取本地点击位置?

时间:2019-10-27 12:39:47

标签: swiftui

具有一些渲染的图像,需要确定相对于图像的拍子位置。看起来很简单,但是找不到答案

  var body: some View {
    VStack {
      Image(uiImage: drawRectangle()) // some rendered image
        .onTapGesture {
          // print(x, y)?
        }

2 个答案:

答案 0 :(得分:1)

找到了这个解决方案:

        .gesture(
            DragGesture(minimumDistance: 0, coordinateSpace: .global)
                .onChanged { value in
                  self.position = value.location
                }
                .onEnded { _ in
                  self.position = .zero
                }
        )

设置minimumDistance: 0将立即调用onChanged

答案 1 :(得分:1)

我确实尝试将DragGestureminimumDistance: 0一起使用,但是它劫持了表格视图的滚动手势。

因此,我更喜欢使用适当的UITapGestureRecognizer添加到嵌入在UIView SwitUI TappableView中的普通透明UIViewRepresentable中。

struct TappableView: UIViewRepresentable
{
    var tapCallback: (UITapGestureRecognizer) -> Void

    typealias UIViewType = UIView

    func makeCoordinator() -> TappableView.Coordinator
    {
        Coordinator(tapCallback: self.tapCallback)
    }

    func makeUIView(context: UIViewRepresentableContext<TappableView>) -> UIView
    {
        let view = UIView()
        view.addGestureRecognizer(UITapGestureRecognizer(target: context.coordinator, action: #selector(Coordinator.handleTap(sender:))))
        return view
    }

    func updateUIView(_ uiView: UIView, context: UIViewRepresentableContext<TappableView>)
    {
    }

    class Coordinator
    {
        var tapCallback: (UITapGestureRecognizer) -> Void

        init(tapCallback: @escaping (UITapGestureRecognizer) -> Void)
        {
            self.tapCallback = tapCallback
        }

        @objc func handleTap(sender: UITapGestureRecognizer)
        {
            self.tapCallback(sender)
        }
    }
}

然后只需将其作为.overlay添加到要添加水龙头的SwiftUI视图中即可。

.overlay(
    TappableView { gesture in
        // Just use the regular UIKit gesture as you want!
})