如何在 MapView 上点击然后将其传递给默认手势识别器?
Posted
技术标签:
【中文标题】如何在 MapView 上点击然后将其传递给默认手势识别器?【英文标题】:How can I catch tap on MapView and then pass it to default gesture recognizers? 【发布时间】:2012-03-14 10:47:25 【问题描述】:这就是我想要的 - 用户在地图上点击,我的代码被执行,然后系统代码被执行(如果用户点击了注释标注等等......)。
我在地图视图中添加了简单的点击识别器:
UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(mapViewTapped:)];
[self.mapView addGestureRecognizer:tapGestureRecognizer];
[tapGestureRecognizer release];
在 mapViewTapped 内部,我的代码被执行。现在我想通知系统代码点击(例如显示标注)。我怎么做?如何传递我拦截的事件?
【问题讨论】:
【参考方案1】:一种方法是实现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:
中检查点击是否在注释视图上,然后手动选择将显示其标注的注释(并调用@987654328 @委托方法):
-(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];
【讨论】:
谢谢,你的解释不仅有用,而且很详细 非常感谢,您的第二个建议正是我所追求的! 很棒的建议,正是我想要的 这是一个完美的解决方案【参考方案2】: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)
【讨论】:
以上是关于如何在 MapView 上点击然后将其传递给默认手势识别器?的主要内容,如果未能解决你的问题,请参考以下文章
如何将一些信息传递给视图而不将其包含在 URL 中(django 新手)
React Native Expo MapView - 将标记详细信息传递给扩展的底部视图