I have a SwiftUI Map with MapAnnotations. I would like to have an onTap gesture on the Map, so it deselects the selected annotations, and dissmisses a bottom sheet, etc. Also would like to have an onTap gesture on the annotation item (or just having a button as annotation view with an action there), which selects the annotation and do stuff. The problem: whenever I tap the annotation, the map's ontap gesture is triggered too. (When I tap on the map, it only triggers the map's action, so no problems there.) Here's some sample code:
import SwiftUI
import MapKit
import CoreLocation
struct ContentView: View {
@State var region: MKCoordinateRegion =
MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: 47.333,
longitude: 19.222),
span: MKCoordinateSpan(latitudeDelta: 0.002, longitudeDelta: 0.002))
var body: some View {
Map(coordinateRegion: $region,
annotationItems: AnnotationItem.sample) { annotation in
MapAnnotation(coordinate: annotation.location.coordinate) {
VStack {
Circle()
.foregroundColor(.red)
.frame(width: 50)
Text(annotation.name)
}
.onTapGesture {
print(">> tapped child")
}
}
}
.onTapGesture {
print(">> tapped parent")
}
}
}
I tap on the annotation, then:
>> tapped parent
>> tapped child
I tap on the map, then:
>> tapped parent
EDIT:
I have tried and didn't work:
- make parent action depend on a boolean, which is set to prevent map's action when child is tapped. See in comment: I can only delay the parents action with this, cannot cancel it.
- add on custom tap gesture for each, and set .exclusivelyBefore(:) modifier on one of them
Currently one little hack seems to work! I change the onTap gesture to a DragGesture with a minimum distance of 0.
and it works! The problem with this solution, is that touching one of the pins while dragging the map, triggers the pin action unintentionally. Thus my answer will not be the accepted one