代码之家  ›  专栏  ›  技术社区  ›  Christophe Debove

触摸时如何将图钉添加到MKMapView(IOS)中?

  •  59
  • Christophe Debove  · 技术社区  · 15 年前

    我必须得到用户在mkmappview上触摸的点的坐标。 我没有和界面生成器一起工作。 你能举个例子吗?

    2 回复  |  直到 7 年前
        1
  •  197
  •   Cœur Gustavo Armenta    7 年前

    你可以用 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 .

        2
  •  33
  •   Bhavesh Bansal    8 年前

    正在创建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)
    }