简体   繁体   English

如何在IOS上管理MKAnnotationView的拖放?

[英]how to manage drag and drop for MKAnnotationView on IOS?

I'm working without InterfaceBuilder . 我在没有InterfaceBuilder情况下工作。

I've an instance of MKAnnotationView with setDraggable on YES , In My MKMapView my annotation view is displayed and I can drag and drop it. 我有一个实例MKAnnotationViewsetDraggable ,在我MKMapView我的标注视图显示,我可以将它拖放。

How can I execute an method when the drop action is performed? 如何执行放置操作时执行方法? In this method I need the new coordonates of my annotation view. 在这个方法中,我需要我的注释视图的新协调。

If you've setup your MKAnnotation object with a setCoordinate method properly, then in the didChangeDragState method, the new coordinate should already be in the annotation object: 如果您正确地使用setCoordinate方法设置MKAnnotation对象,那么在didChangeDragState方法中,新坐标应该已经在注释对象中:

- (void)mapView:(MKMapView *)mapView 
        annotationView:(MKAnnotationView *)annotationView 
        didChangeDragState:(MKAnnotationViewDragState)newState 
        fromOldState:(MKAnnotationViewDragState)oldState 
{
    if (newState == MKAnnotationViewDragStateEnding)
    {
        CLLocationCoordinate2D droppedAt = annotationView.annotation.coordinate;
        NSLog(@"dropped at %f,%f", droppedAt.latitude, droppedAt.longitude);
    }
}

For reference, see the "Marking Your Annotation View as Draggable" section in the docs here . 有关参考,请参阅此处文档中的 “将注释视图标记为可拖动”部分。 If your app needs to work in an OS earlier than 4.x, the dragging requires more manual work. 如果您的应用需要在早于4.x的操作系统中工作,则拖动需要更多的手动工作。 The link in the docs also points to an example of how to do that if you need to. 文档中的链接还指出了如果需要如何执行此操作的示例。

you may also want to add the following: 您可能还想添加以下内容:

if (newState == MKAnnotationViewDragStateStarting) {
    annotationView.dragState = MKAnnotationViewDragStateDragging;
}
else if (newState == MKAnnotationViewDragStateEnding || newState == MKAnnotationViewDragStateCanceling) {
    annotationView.dragState = MKAnnotationViewDragStateNone;
}

since MKAnnotationView doesn't change its drag state accurately (which could make your map pan with your annotation even after you stop dragging) 因为MKAnnotationView没有准确地改变它的拖动状态(即使你停止拖动也可以使你的地图平移你的注释)

Swift solution : Swift解决方案:

func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, didChange newState: MKAnnotationViewDragState, fromOldState oldState: MKAnnotationViewDragState)
    {
        if (newState == MKAnnotationViewDragState.ending)
        {
            let droppedAt = view.annotation?.coordinate
            print("dropped at : ", droppedAt?.latitude ?? 0.0, droppedAt?.longitude ?? 0.0);
            view.setDragState(.none, animated: true)    
        }
        if (newState == .canceling )
        {
            view.setDragState(.none, animated: true)           
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM