【问题标题】:How undo a MapKit annotation drag如何撤消 MapKit 注释拖动
【发布时间】:2025-12-23 02:35:16
【问题描述】:

如果在 mapView didChangeDragState 中检测到注释被拖到了不需要的位置,我可以在 mapView:didChangeDragState 中取消拖拽。

 case .Dragging:  
            let inColorado = StateOutline.inColorado(view.annotation!.coordinate)
            if !inColorado {
                view.dragState = .Canceling
            }

不幸的是,这会将大头针留在取消拖动的不需要位置的位置。

有人想将注释设置为

  • 一个有效的坐标
  • 或恢复到拖动前的坐标
  • 或设置为拖动的最后一个有效位置

    case .Canceling:
            view.annotation!.coordinate = StateOutline.coloradoCenter()
            view.dragState = .None
        }
    

不允许该坐标设置,因为 view.annotation!.coordinate 是一个 get-only 属性。

如何撤消注释拖动?

不需要考虑使用 MKAnnotation setCoordinate - 它在 iOS 8.3 中被删除。

唯一想到的就是用新的注释替换该注释并在其上设置坐标。理想情况下,引脚坐标将设置为其最后一个有效位置。

【问题讨论】:

    标签: ios swift mkannotation mkannotationview


    【解决方案1】:

    您的错误是认为无法设置注释的坐标。它可以。 MKAnnotation 协议没有规定可设置的坐标,但所有实际采用者都有一个。只需使用MKPointAnnotation。它的coordinate 是可设置的。你甚至可能已经在使用了!

    public class MKPointAnnotation : MKShape {
        public var coordinate: CLLocationCoordinate2D
    }
    

    您甚至可以编写自己的 MKAnnotation 采用者:

    import UIKit
    import MapKit
    
    class MyAnnotation : NSObject, MKAnnotation {
        dynamic var coordinate : CLLocationCoordinate2D
        var title: String?
        var subtitle: String?
    
        init(location coord:CLLocationCoordinate2D) {
            self.coordinate = coord
            super.init()
        }
    }
    

    【讨论】:

    • 感谢您的帮助。已经有了我自己的注释类,脱离 MKPointAnnotation。什么有效,将逻辑放在 .Ending 案例中:让 annotation = view.annotation as!我的注释!我缺少的关键是要获得带有可设置坐标的注释。用户仍然可以将图钉拖动到任何地方(即使将 zoomEnabled 和 scrollEnabled 设置为 false,也会导致地图视图滚动)。