如何在触摸时将推针添加到MKMapView(IOS)?

Chr*_*ove 59 iphone mkmapview pushpin ios

我不得不得到用户触摸MKMapView的点的协调.我没有使用Interface Builder.你能给我一个例子或链接吗?

非常感谢

小智 195

您可以使用UILongPressGestureRecognizer进行此操作.无论您在何处创建或初始化mapview,请先将识别器附加到其中:

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];
Run Code Online (Sandbox Code Playgroud)

然后在手势处理程序中:

- (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];
}
Run Code Online (Sandbox Code Playgroud)

YourMKAnnotationClass是您定义的符合MKAnnotation协议的类.如果您的应用程序仅在iOS 4.0或更高版本上运行,则可以使用预定义的MKPointAnnotation类.

有关创建自己的MKAnnotation类的示例,请参阅示例应用程序WeatherMapMapCallouts.

  • 很棒的回答,谢谢.我个人将if语句翻转为`==`,如果*不是*`UIGestureRecognizerStateBegan`则返回.即使用户仍然拿着我想要的地图(以及官方地图应用程序如何操作),执行此操作也会在指定时间后丢弃该引脚. (6认同)

Vla*_*eys 33

感谢Anna提供了这么好的答案!如果有人感兴趣,这是Swift版本(答案已更新为Swift 4.1语法).

创建UILongPressGestureRecognizer:

let longPressRecogniser = UILongPressGestureRecognizer(target: self, action: #selector(MapViewController.handleLongPress(_:)))
longPressRecogniser.minimumPressDuration = 1.0
mapView.addGestureRecognizer(longPressRecogniser)
Run Code Online (Sandbox Code Playgroud)

处理手势:

@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)
}
Run Code Online (Sandbox Code Playgroud)

  • 可以使用_**let longPressRecogniser = UILongPressGestureRecognizer(target:self,action:"handleLongPress:")**_ (2认同)