如何在MapView上点击,然后将其传递给默认手势识别器?

时间:2012-03-14 10:47:26

标签: iphone ios mkmapview uigesturerecognizer

这就是我想要的 - 用户点击地图,我的代码被执行然后系统代码被执行(如果用户点击了注释标注等...)。

我在地图视图中添加了简单的点按识别器:

UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(mapViewTapped:)];
[self.mapView addGestureRecognizer:tapGestureRecognizer];
[tapGestureRecognizer release];

在mapViewTapped中,我的代码被执行了。现在我想通知tap的系统代码(例如显示callout)。我怎么做?如何通过我拦截的事件?

2 个答案:

答案 0 :(得分:23)

一种方法是实施UIGestureRecognizerDelegate方法gestureRecognizer:shouldRecognizeSimultaneouslyWithGestureRecognizer:并在其中返回YES

//add <UIGestureRecognizerDelegate> to .h to avoid compiler warning

//add this where you create tapGestureRecognizer...
tapGestureRecognizer.delegate = self;

-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer 
    shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    return YES;
}

现在您的mapViewTapped:将被调用,然后地图视图的识别器将调用其方法。如果点击位于注释视图上,则地图视图将显示其标注(如果您已实施,则会调用didSelectAnnotationView委托方法。)


另一种方法是,如果您需要更多控制,那么在mapViewTapped:中,您可以检查点击是否在注释视图上,然后手动选择将显示其标注的注释(并调用该注释),而不是执行上述操作。 didSelectAnnotationView委托方法):

-(void)mapViewTapped:(UITapGestureRecognizer *)tgr
{
    CGPoint p = [tgr locationInView:mapView];

    UIView *v = [mapView hitTest:p withEvent:nil];

    id<MKAnnotation> ann = nil;

    if ([v isKindOfClass:[MKAnnotationView class]])
    {
        //annotation view was tapped, select it...
        ann = ((MKAnnotationView *)v).annotation;
        [mapView selectAnnotation:ann animated:YES];
    }
    else
    {
        //annotation view was not tapped, deselect if some ann is selected...
        if (mapView.selectedAnnotations.count != 0)
        {
            ann = [mapView.selectedAnnotations objectAtIndex:0];
            [mapView deselectAnnotation:ann animated:YES];
        }
    }
}

答案 1 :(得分:0)

Swift 爱好者的第二个选择:

@objc private func mapViewTapped(sender: UITapGestureRecognizer) {
    let point = sender.location(in: mapView)
    if let view = mapView.hitTest(point, with: nil) as? MKAnnotationView {
        if let annotation = view.annotation {
            mapView.selectAnnotation(annotation, animated: true)
        }
    } else {
        let selected = mapView.selectedAnnotations
        if selected.count != 0 {
            mapView.deselectAnnotation(selected[0], animated: true)
        }
    }
}