如何在 MKMapView 上捕获点击手势 [英] How to capture Tap gesture on MKMapView
问题描述
我正在尝试在我的 MKMapView
上捕获点击事件,这样我可以在用户点击的位置放置一个 MKPinAnnotation
.基本上我有一张用 MKOverlayViews
覆盖的地图(显示建筑物的覆盖),我想在用户点击该覆盖时通过放置 MKPinAnnotaion
为他们提供更多信息并在标注中显示更多信息.谢谢你.
I am trying to capture tap event on my MKMapView
, this way I can drop a MKPinAnnotation
on the point where user tapped. Basically I have a map overlayed with MKOverlayViews
(an overlay showing a building) and I would like to give user more information about that Overlay when they tap on it by dropping a MKPinAnnotaion
and showing more information in the callout.
Thank you.
推荐答案
您可以使用 UIGestureRecognizer
来检测地图视图上的触摸.
You can use a UIGestureRecognizer
to detect touches on the map view.
不过,我建议寻找双击(UITapGestureRecognizer
)或长按(UILongPressGestureRecognizer
),而不是单击.单击可能会干扰用户尝试单击图钉或标注本身.
Instead of a single tap, however, I would suggest looking for a double tap (UITapGestureRecognizer
) or a long press (UILongPressGestureRecognizer
). A single tap might interfere with the user trying to single tap on the pin or callout itself.
在您设置地图视图的位置(例如在 viewDidLoad
中),将手势识别器附加到地图视图:
In the place where you setup the map view (in viewDidLoad
for example), attach the gesture recognizer to the map view:
UITapGestureRecognizer *tgr = [[UITapGestureRecognizer alloc]
initWithTarget:self action:@selector(handleGesture:)];
tgr.numberOfTapsRequired = 2;
tgr.numberOfTouchesRequired = 1;
[mapView addGestureRecognizer:tgr];
[tgr release];
或使用长按:
UILongPressGestureRecognizer *lpgr = [[UILongPressGestureRecognizer alloc]
initWithTarget:self action:@selector(handleGesture:)];
lpgr.minimumPressDuration = 2.0; //user must press for 2 seconds
[mapView addGestureRecognizer:lpgr];
[lpgr release];
在 handleGesture:
方法中:
- (void)handleGesture:(UIGestureRecognizer *)gestureRecognizer
{
if (gestureRecognizer.state != UIGestureRecognizerStateEnded)
return;
CGPoint touchPoint = [gestureRecognizer locationInView:mapView];
CLLocationCoordinate2D touchMapCoordinate =
[mapView convertPoint:touchPoint toCoordinateFromView:mapView];
MKPointAnnotation *pa = [[MKPointAnnotation alloc] init];
pa.coordinate = touchMapCoordinate;
pa.title = @"Hello";
[mapView addAnnotation:pa];
[pa release];
}
这篇关于如何在 MKMapView 上捕获点击手势的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!