Reputation: 475
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?
Upvotes: 16
Views: 5879
Reputation: 2257
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)
}
)
Upvotes: 2
Reputation: 258365
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.
Upvotes: 6