Перетащите пользовательский вид аннотаций - PullRequest
0 голосов
/ 30 мая 2020

У меня есть собственный Annotation класс 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
}

Что еще мне нужно? Я хочу нажать на аннотацию, остаться нажатым и go в другое положение, затем отпустить палец, и аннотация останется на месте.

1 Ответ

1 голос
/ 30 мая 2020

При перетаскивании необходимо изменить coordinate основной аннотации. Он не может этого сделать, если он доступен только для чтения. Итак, если вы хотите сделать его перетаскиваемым, вы должны указать свойству coordinate сеттер:

public var coordinate: CLLocationCoordinate2D {
    get {
        CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
    }
    set {
        latitude = newValue.latitude
        longitude = newValue.longitude
    }
}
...