Does swiftui have a hitTest equivalent?

Viewed 2364

I have a gesture's touch location in global coordinate space from which I'd like to figure out the Rectangle that's at those coordinates. How can I do that?

2 Answers

No it does not. By SwiftUI design one should explicitly add tap gesture to a view which is going to handle action. So, if my view would have some tappable elements I have to make them as view and attach gesture to it, like

var body: some View {
    HStack {
        Rectangle()
            .fill(Color.red.opacity(0.2))
            .frame(width: 300, height: 300)
            .clipShape(Circle())
            .onTapGesture {
                print("Tapped!")
            }
    }
}

If some views can overlap then inactive view should be marked with .allowsHitTesting(false) modifier.

There is a .allowsHitTesting(_:) modifier which can be used to control whether a view should recognize touches.

https://developer.apple.com/documentation/swiftui/view/allowshittesting(_:)

To obtain an exact location of a tap, you can use a drag gesture recognizer with zero distance:

Rectangle()
   .gesture(
       DragGesture(minimumDistance: 0)
               .onEnded { value in
                    let location = value.location
                    print(location)
                }
       )
Related