59

我必须获取用户在 MKMapView 上触摸的点的坐标。我没有使用 Interface Builder。你能给我一个例子吗?

4

2 回答 2

196

您可以为此使用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

于 2010-10-18T15:38:47.047 回答
34

感谢 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)
}
于 2015-04-06T06:24:07.543 回答