如何使用 Swift 中的 MapKit 使用户能够将注释从 map 中的一个位置拖动到另一个位置?当我的 map View 委托(delegate)创建注释 View 时,我已将注释 View 设置为可拖动,如下所示:
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
}
结果是用户可以有点拖动注释 - 但只能拖动一次。之后,注释变得无法拖动,更糟糕的是,注释现在不再“属于” map - 当滚动/平移 map 时,注释保持静止而不是随 map 滚动/平移。我做错了什么?
最佳答案
通过将 isDraggable
设置为 true
来标记注释 View 是不够的。您还必须在 map View 委托(delegate)中实现 mapView(_:annotationView:didChange:fromOldState:)
- 并且(更重要的是)此实现不能为空! 相反,您的实现必须至少将拖动状态从传入参数传达给注释 View ,如下所示:
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 如此清楚地解释了这一点。我不能要求任何功劳!我在这里的回答只是将该代码翻译成 Swift。)
关于iOS Swift MapKit 使注释可由用户拖动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29776853/