2010-10-18 72 views

回答

190

你可以使用这个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]; 

然后在手势处理机:

- (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类的示例,请参阅示例应用程序WeatherMapMapCallouts

+0

谢谢你,它的工作 – 2010-10-18 17:58:12

+6

真棒回答,谢谢。就我个人而言,我将if语句翻转成了一个'==',所以如果*不是*'UIGestureRecognizerStateBegan',它就会返回。这样做会在指定的时间后丢弃指针,即使用户仍然拿着我想要的地图(以及官方地图应用程序如何操作)。 – 2011-05-07 07:42:08

+0

我只想说我将自己的答案贯彻到了我的项目中,并且它像一个魅力一样工作。谢谢你最好的回答。 – DoubleDunk 2011-07-04 05:31:27

32

感谢安娜提供这样一个很好的答案!如果有人感兴趣,这里是一个Swift版本(答案已经更新为Swift 3.0语法)。

创建UILongPressGestureRecognizer:

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

处理手势:

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) 
} 
+0

哇......我没有注意到这一点,花了很长时间把它转换。 – 2015-05-25 19:14:51

+2

可以使用_ ** let longPressRecogniser = UILongPressGestureRecognizer(target:self,action:“handleLongPress:”)** _ – 2015-10-07 05:13:06

+0

@Dx_ yes您可以使用,因为识别器未被修改。识别器中的属性正在修改中。 – 3366784 2016-08-07 18:02:32