Пользовательские кластерные аннотации на MapKit cra sh при быстром перетаскивании карты или изменении уровня масштабирования - PullRequest
0 голосов
/ 12 апреля 2020

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

- [MKPointAnnotation memberAnnotations]: нераспознанный селектор отправлен в экземпляр 0x281396c00

Я предполагаю, что компилятор пытается получить информацию аннотации, но не могу найти данные. Поскольку я довольно новичок в Swift, я не вижу, чего мне не хватает. Ваша помощь будет принята с благодарностью.

У меня есть довольно базовая c настройка для отображения карты в SwiftUI. В основном файле я вызываю MapView из MapView.swift

struct MapView: UIViewRepresentable {

    @ObservedObject var store = DataStoreMap()

    func makeCoordinator() -> MapViewCoordinator {
        MapViewCoordinator(self)
    }

    func makeUIView(context: Context) -> MKMapView{
        MKMapView(frame: .zero)
    }

    func updateUIView(_ view: MKMapView, context: Context){

        let location = getUserLocation()
        let chargers = store.chargers

        let coordinate = CLLocationCoordinate2D(latitude: location.latitude, longitude: location.longitude)
        let span = MKCoordinateSpan(latitudeDelta: 0.03, longitudeDelta: 0.03)
        let region = MKCoordinateRegion(center: coordinate, span: span)
        view.setRegion(region, animated: true)

        for charger in chargers {
            let annotation = MKPointAnnotation()
            annotation.coordinate = CLLocationCoordinate2D(latitude: charger.addressInfo.latitude, longitude: charger.addressInfo.longitude)
            view.delegate = context.coordinator
            view.addAnnotation(annotation)
        }

    }
}

Также в этот файл включен мой пользовательский класс аннотаций.

class MapViewCoordinator: NSObject, MKMapViewDelegate {

    var mapViewController: MapView

    init(_ control: MapView) {
        self.mapViewController = control
    }

    func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
        //Custom View for Annotation
        var annotationView = MKMarkerAnnotationView()
        annotationView.canShowCallout = true

        let identifier = "laadpaal"

        if let dequedView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier) as? MKMarkerAnnotationView {
            annotationView = dequedView
        } else {
            annotationView = MKMarkerAnnotationView(annotation: annotation, reuseIdentifier: identifier)
        }

        annotationView.markerTintColor = .some(.systemBlue)
        annotationView.glyphImage = UIImage(named: "car1")
        annotationView.glyphTintColor = .yellow
        annotationView.clusteringIdentifier = identifier

        return annotationView
    }
}

1 Ответ

1 голос
/ 23 апреля 2020

Причина вашего cra * sh заключается в том, что вы не учитываете другие аннотации, запрошенные набором карт (например, MKUserLocation). Вы запускаете это из-за автоматической кластеризации c, когда вы устанавливаете clusteringIdentifier в значение, отличное от nil.

Просто верните nil, если вы хотите разобраться с аннотацией самостоятельно, так что MKMapView использует обработку по умолчанию:

    func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
        if annotation is MKUserLocation { return nil }
        if annotation is MKClusterAnnotation { return nil }

        let view = mapView.dequeueReusableAnnotationView(withIdentifier: "identifier", for: annotation)
        view.clusteringIdentifier = "clusterIdentifer"
        // …

        return view
    }

Если вы когда-нибудь захотите настроить аннотации кластера, просто добавьте специальный регистр для MKClusterAnnotation. И если вы показываете местоположение пользователя, не забудьте вернуть nil для MKUserLocation, если вы хотите использовать синюю точку по умолчанию.

...