I have a MKMapView
. I added a UITapGestureRecognizer
with a single tap.
I now want to add a MKAnnotationView
to the map. I can
Your solution should be making use of the - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
method on your delegate.
In this method, you can check if the touch was on one of your annotations, and if so, return NO
so that your gestureRecognizer
isn't activated.
Objective-C:
- (NSArray*)getTappedAnnotations:(UITouch*)touch
{
NSMutableArray* tappedAnnotations = [NSMutableArray array];
for(id annotation in self.mapView.annotations) {
MKAnnotationView* view = [self.mapView viewForAnnotation:annotation];
CGPoint location = [touch locationInView:view];
if(CGRectContainsPoint(view.bounds, location)) {
[tappedAnnotations addObject:view];
}
}
return tappedAnnotations;
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
return [self getTappedAnnotations:touch].count > 0;
}
Swift:
private func getTappedAnnotations(touch touch: UITouch) -> [MKAnnotationView] {
var tappedAnnotations: [MKAnnotationView] = []
for annotation in self.mapView.annotations {
if let annotationView: MKAnnotationView = self.mapView.viewForAnnotation(annotation) {
let annotationPoint = touch.locationInView(annotationView)
if CGRectContainsPoint(annotationView.bounds, annotationPoint) {
tappedAnnotations.append(annotationView)
}
}
}
return tappedAnnotations
}
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool {
return self.getTappedAnnotations(touch: touch).count > 0
}