iOS Swift MapKit使用户可以拖动注释吗?

mat*_*att 15 draggable mapkit mkannotationview ios swift

如何使用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
}
Run Code Online (Sandbox Code Playgroud)

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

mat*_*att 27

仅通过设置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
    }
}
Run Code Online (Sandbox Code Playgroud)

一旦这样做,用户就可以正确地拖动注释.

(非常感谢这个答案可以清楚地解释这一点.我不能说任何功劳!我的答案仅仅是将代码翻译成Swift.)

  • 此解决方案是否仍然适用(iOS 11)?我遵循了解决方案,但是从未调用过mapView(_:annotationView:didChange:fromOldState :)方法。 (2认同)