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

Meg*_*anX 11 iphone mkmapview uigesturerecognizer ios

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

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

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

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

小智 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;
}
Run Code Online (Sandbox Code Playgroud)

现在您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];
        }
    }
}
Run Code Online (Sandbox Code Playgroud)