问题描述
这就是我想要的 - 用户点击地图,我的代码被执行然后系统代码被执行(如果用户点击了注释标注等等...)。
Here is what I want - user taps on the map, my code gets executed and then system code is executed (if user clicked on annotation callout is presented etc...).
我在地图视图中添加了简单的点击识别器:
I added simple tap recognizer to map view:
UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(mapViewTapped:)];
[self.mapView addGestureRecognizer:tapGestureRecognizer];
[tapGestureRecognizer release];
在mapViewTapped中我的代码被执行了。现在我想通知tap的系统代码(例如显示callout)。我怎么做?如何传递我拦截的事件?
Inside mapViewTapped my code gets executed. Now I want to notify system code of tap (for example to show callout). How do I do that? How to pass event that I intercepted?
推荐答案
一种方法是实现 UIGestureRecognizerDelegate
方法 gestureRecognizer:shouldRecognizeSimultaneouslyWithGestureRecognizer:
并在其中返回 YES
:
One way is to implement the UIGestureRecognizerDelegate
method gestureRecognizer:shouldRecognizeSimultaneouslyWithGestureRecognizer:
and return YES
in it:
//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
委托方法)。
Now your mapViewTapped:
will get called and then the map view's recognizer will call its method. If the tap was on an annotation view, the map view will show its callout (and the didSelectAnnotationView
delegate method will get called if you've implemented it).
另一种方式,如果你需要更多的控制,那么而不是在你的 mapViewTapped中执行上述操作:
您可以检查点击是否在注释视图上,然后手动选择注释,然后显示其标注(并调用 didSelectAnnotationView
委托方法):
Another way, if you need more control, then instead of doing the above, in your mapViewTapped:
you can check if the tap was on an annotation view and then manually select the annotation which will then show its callout (and call the didSelectAnnotationView
delegate method):
-(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];
}
}
}
这篇关于如何在MapView上点击,然后将其传递给默认手势识别器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!