拖动自定义注记Swift

问题描述 投票:0回答:1

我有我的CoreData自定义注释类:

extension Annotation: MKAnnotation {

    public var coordinate: CLLocationCoordinate2D {
        let cllCoordinate = CLLocationCoordinate2D(latitude: self.latitude, longitude: self.longitude)
        return cllCoordinate
    }

    public var title: String? {
        return self.objectId
    }

    class func keyPathsForValuesAffectingCoordinate() -> Set<String> {
        return Set<String>([ #keyPath(latitude), #keyPath(longitude) ])
    }

    @nonobjc public class func fetchRequest() -> NSFetchRequest<Annotation> {
        return NSFetchRequest<Annotation>(entityName: "Annotation")
    }

    @NSManaged public var latitude: Double
    @NSManaged public var longitude: Double
    @NSManaged public var dateTime: Date
    @NSManaged public var type: String
    @NSManaged public var objectId: String?

}

与fetchedResultsController结合使用,可以添加和删除注释。但是现在想要将注释拖到另一个位置。但是,仅将.isdraggable设置为true并不是全部。我找不到更新的说明如何将其集成。

这里是我的viewFor方法:

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
        guard annotation is Annotation else { return nil }

        let identifier = "Annotation"
        var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier)

        if annotationView == nil {
            annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: identifier)
            annotationView?.isDraggable = true
            annotationView?.canShowCallout = true
        } else {
            annotationView!.annotation = annotation
        }

        let customAnno = annotation as! Annotation
        let image = UIImage(named: customAnno.type)
        annotationView!.image = image

        return annotationView
    }

我还需要什么?我想按一下注释,保持按下状态并转到另一个位置,然后松开手指,注释就留在那里。

请帮助:)

谢谢,丹尼尔。

swift mkmapview draggable mkannotation mkannotationview
1个回答
0
投票

拖动时,它会更改基础注释的coordinate。因此,如果要使其可拖动,则必须为coordinate属性设置一个setter:

public var coordinate: CLLocationCoordinate2D {
    get {
        CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
    }
    set {
        latitude = newValue.latitude
        longitude = newValue.longitude
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.