MKAnnotationView and tap detection

前端 未结 6 1285
攒了一身酷
攒了一身酷 2020-12-09 21:29

I have a MKMapView. I added a UITapGestureRecognizer with a single tap.

I now want to add a MKAnnotationView to the map. I can

6条回答
  •  南方客
    南方客 (楼主)
    2020-12-09 21:34

    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
    }
    

提交回复
热议问题