我需要获取用户在MKMapView上触摸的点的坐标。 我没有使用Interface Builder。 你能给我一个例子吗?
您可以使用 UILongPressGestureRecognizer 来实现此功能。在创建或初始化地图视图的任何位置,首先将识别器附加到它上面:
UILongPressGestureRecognizer *lpgr = [[UILongPressGestureRecognizer alloc]
initWithTarget:self action:@selector(handleLongPress:)];
lpgr.minimumPressDuration = 2.0; //user needs to press for 2 seconds
[self.mapView addGestureRecognizer:lpgr];
[lpgr release];
然后在手势处理程序中:
- (void)handleLongPress:(UIGestureRecognizer *)gestureRecognizer
{
if (gestureRecognizer.state != UIGestureRecognizerStateBegan)
return;
CGPoint touchPoint = [gestureRecognizer locationInView:self.mapView];
CLLocationCoordinate2D touchMapCoordinate =
[self.mapView convertPoint:touchPoint toCoordinateFromView:self.mapView];
YourMKAnnotationClass *annot = [[YourMKAnnotationClass alloc] init];
annot.coordinate = touchMapCoordinate;
[self.mapView addAnnotation:annot];
[annot release];
}
YourMKAnnotationClass是你定义的一个类,遵循MKAnnotation协议。如果你的应用程序只在iOS 4.0或更高版本上运行,可以使用预定义的MKPointAnnotation类。
关于如何创建自己的MKAnnotation类,可以参考示例应用程序MapCallouts。
感谢Anna提供如此好的答案!如果有人感兴趣,这里有Swift版本(答案已更新为Swift 4.1语法)。
创建UILongPressGestureRecognizer:
let longPressRecogniser = UILongPressGestureRecognizer(target: self, action: #selector(MapViewController.handleLongPress(_:)))
longPressRecogniser.minimumPressDuration = 1.0
mapView.addGestureRecognizer(longPressRecogniser)
处理手势:
@objc func handleLongPress(_ gestureRecognizer : UIGestureRecognizer){
if gestureRecognizer.state != .began { return }
let touchPoint = gestureRecognizer.location(in: mapView)
let touchMapCoordinate = mapView.convert(touchPoint, toCoordinateFrom: mapView)
let album = Album(coordinate: touchMapCoordinate, context: sharedContext)
mapView.addAnnotation(album)
}
==
,这样它返回的就是不是UIGestureRecognizerStateBegan
。这么做将在指定时间后放置图钉,即使用户仍然持有地图,这对我来说是理想的(也是官方Maps应用程序的操作方式)。 - William Denniss