2015-04-21 33 views
10

我如何使用Swift中的MapKit让用户从地图上的一个位置拖动一个注释到另一个位置?我已经设置了标注视图为可拖动,当我的地图视图的委托创建注释来看,是这样的:iOS Swift MapKit使用户可以拖动注释吗?

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { 
    var v : MKAnnotationView! = nil 
    if annotation is MyAnnotation { 
     let ident = "bike" 
     v = mapView.dequeueReusableAnnotationView(withIdentifier:ident) 
     if v == nil { 
      v = MyAnnotationView(annotation:annotation, reuseIdentifier:ident) 
     } 
     v.annotation = annotation 
     v.isDraggable = true 
    } 
    return v 
} 

其结果是,用户可以排序拖动注释的 - 但只有一次。之后,注释变得无法拖动,甚至更糟糕的是,注释现在不再“属于”地图 - 当地图滚动/平移时,注释保持静止而不是滚动/平移地图。我究竟做错了什么?

回答

17

仅通过将isDraggable设置为true来标记注释视图是不够的。你还必须在你的地图视图委托中实现mapView(_:annotationView:didChange:fromOldState:) - (更重要的)这个实现不能为空!相反,您的实现必须在最低限度,从传入的参数传达拖动状态到注解视图,就像这样:

func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, didChange newState: MKAnnotationViewDragState, fromOldState oldState: MKAnnotationViewDragState) { 
    switch newState { 
    case .starting: 
     view.dragState = .dragging 
    case .ending, .canceling: 
     view.dragState = .none 
    default: break 
    } 
} 

一旦你这样做,注释将用户正确拖动。

(非常感谢this answer解释这个这么清楚,我不能要求任何信用!在这里我的答案仅仅是代码到斯威夫特的翻译。)

+0

是该解决方案仍然适用(iOS版11)?我跟着解决方案,但'mapView(_:annotationView:didChange:fromOldState ::)'方法永远不会被调用。 – mert