How to make custom MKAnnotation draggable

六月ゝ 毕业季﹏ 提交于 2019-12-05 15:04:29

As already mentioned, for an annotation to be draggable, it must implement a setCoordinate: method.

Additionally, since iOS 7, you may also need to implement the mapView:annotationView:didChangeDragState: method (see Draggable Pin does not have a fixed position on map and iOS MapKit dragged annotations (MKAnnotationView) no longer pan with map).

You can either implement the setCoordinate: method explicitly yourself or just declare a writeable coordinate property (named exactly like that) and synthesize it (and the getter and setter methods will be automatically implemented for you).

(Note that if you use the pre-defined MKPointAnnotation class, you don't need to do this because that class already implements a settable coordinate property.)


In your NavigationAnnotation class, to implement the explicit, manual solution to work with the existing theCoordinate property, just add the setCoordinate: method to your class implementation (keep the existing getter method):

-(void)setCoordinate:(CLLocationCoordinate2D)newCoordinate
{
    self.theCoordinate = newCoordinate;
}


You may also need to implement the didChangeDragState: method in the class that implements the map view delegate (the same one that has the viewForAnnotation method) otherwise after dragging, the annotation view will hover in-place above the map even while it is panned or zoomed underneath. An example implementation of the method as given by Chris K. in his answer:

- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)annotationView didChangeDragState:(MKAnnotationViewDragState)newState fromOldState:(MKAnnotationViewDragState)oldState
{
    if (newState == MKAnnotationViewDragStateStarting)
    {
        annotationView.dragState = MKAnnotationViewDragStateDragging;
    }
    else if (newState == MKAnnotationViewDragStateEnding || newState == MKAnnotationViewDragStateCanceling)
    {
        annotationView.dragState = MKAnnotationViewDragStateNone;
    }
}

Just went through this issue... After some struggling, reason was different (title, coordinate were ok), so adding possible cause here

In my annotation view, I did override - (void) setSelected:(BOOL)selected

Without calling [super setSelected:selected]; This prevented the dragging from occuring...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!