首页 > 解决方案 > 自定义 MKAnnotationView 想要再次被点击

问题描述

我的自定义 MKAnnotationView 出现问题。我从我的 REST api 下载了放置它的坐标,并使用以下代码将图钉放置在地图上:

private func refreshMapView(andCenterMap: Bool){
    DispatchQueue.main.async { [weak self] in
        guard let self = self else {
            return
        }

        self.mapView.addAnnotations(self.spotsArray)
        if andCenterMap {
            self.centerMap(at: self.mapView.userLocation.coordinate)
        }
    }
}

放置大头针的我会自动缩放地图。

这里是自定义注释创建的代码:

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
    // Do not touch the annotation of the user location
    if annotation.isKind(of: MKUserLocation.self){
        return nil
    }

    let annoIdentifier = "SPOT"
    var annotationView: MKAnnotationView?

    if let dequeued = mapView.dequeueReusableAnnotationView(withIdentifier: annoIdentifier) {
        annotationView = dequeued
    }else{
        let av = MKAnnotationView(annotation: annotation, reuseIdentifier: annoIdentifier)
        annotationView = av
    }

    // Changing the image of the pin
    annotationView!.annotation = annotation
    if let image = UIImage(named: "map_pin") {
        annotationView!.image = image
        let deltaY = image.size.height/2
        annotationView!.centerOffset = CGPoint(x: 0.0, y: -deltaY)
    }else{
        annotationView!.image = nil
    }

    return annotationView
}

如您所见,我的自定义图钉正在使用此图像(@1x、@2x、@3x)

map_pin map_pin@2x map_pin@3x

点击的我想显示“详细视图”,我使用注释作为发件人,以便在下一个视图中获得我需要的所有信息。这里的代码:

func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
        guard let ann = view.annotation else {
            return
        }
        if ann.isKind(of: MKUserLocation.self){
            return
        }
        self.performSegue(withIdentifier: "showDetailSegue", sender: ann)
}

所以我展示了我需要的所有数据,然后我可以回到“地图视图”。

问题是:

在地图视图中,如果我想再次选择相同的注释,则不再可点击。

我可以看到它(在正确的位置),但只有当我稍微放大一点并点击“周围”注释时才能再次选择它。

任何建议如何解决这个问题?

提前致谢!

标签: swiftmapkitmkannotationview

解决方案


添加这个结尾didSelect

mapView.deselectAnnotation(ann,animated:false)

推荐阅读