iOS Swift MapKit使用户可以拖动注释吗? [英] iOS Swift MapKit making an annotation draggable by the user?

查看:113
本文介绍了iOS Swift MapKit使用户可以拖动注释吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用Swift中的MapKit让用户在地图中将注释从一个位置拖到另一个位置?我已将注释视图设置为可拖动,当我的地图视图委托创建注释视图时,如下所示:

How do I make it possible, using MapKit in Swift, for the user to drag an annotation from one position to another within the map? I have set the annotation view to be draggable, when my map view delegate creates the annotation view, like this:

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
}

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

The result is that the user can sort of drag the annotation - but only once. After that, the annotation becomes impossible to drag, and even worse, the annotation now no longer "belongs" to map - when the map is scrolled / panned, the annotation holds still rather than scrolling / panning with the map. What am I doing wrong?

推荐答案

仅通过设置 isDraggable标记注释视图是不够的 true 。您还必须在地图视图委托中实现 mapView(_:annotationView:didChange:fromOldState:) - 并且(更重要的)此实现不能为空! 相反,您的实现必须至少将拖动状态从传入参数传递到注释视图,如下所示:

It isn't enough to mark the annotation view by setting isDraggable to true. You must also implement mapView(_:annotationView:didChange:fromOldState:) in your map view delegate - and (even more important) this implementation must not be empty! Rather, your implementation must, at a minimum, communicate the drag state from the incoming parameters to the annotation view, like this:

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
    }
}

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

Once you do that, the annotation will be properly draggable by the user.

(非常感谢这个答案,以便清楚地解释这一点。我不能要求任何可靠的它!我在这里的答案仅仅是将代码翻译成Swift。)

(Many thanks to this answer for explaining this so clearly. I can't claim any credit! My answer here is merely a translation of that code into Swift.)

这篇关于iOS Swift MapKit使用户可以拖动注释吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆