如果注释标注与另一个注释重叠,则无法点击该注释标注?

Can't tap an annotation callout if it overlaps with another annotation?

我在 MKMapView 上显示一组注释,使用带有 displayPriority = .required 的自定义 MKMarkerAnnotationView,这样就没有聚类或隐藏,UIButton作为其 rightCalloutAccessoryView

当我点击地图上的注释时,标注会按预期显示,但是当我点击标注或其附件时,如果点击与地图上的另一个标记重叠,则点击不会注册。

下面是该问题的 Playground 友好示例。请注意标注在与地图上的另一个注释重叠时如何不响应点击。

import MapKit
import PlaygroundSupport

class MapViewController: UIViewController, MKMapViewDelegate {
    override func viewDidLoad() {
        super.viewDidLoad()
    }

    func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView,
                 calloutAccessoryControlTapped control: UIControl) {
        print("Callout tapped!")
    }
}

class CustomAnnotationView: MKMarkerAnnotationView {
    override var annotation: MKAnnotation? {
        willSet {
            canShowCallout = true
            rightCalloutAccessoryView = UIButton(type: .detailDisclosure)
            titleVisibility = .hidden
            subtitleVisibility = .hidden
            displayPriority = .required
        }
    }
}

let mapView = MKMapView(frame: CGRect(x:0, y:0, width:800, height:800))
let controller = MapViewController()
mapView.delegate = controller

mapView.register(CustomAnnotationView.self, forAnnotationViewWithReuseIdentifier: MKMapViewDefaultAnnotationViewReuseIdentifier)

let coordinate1 = CLLocationCoordinate2DMake(37.334922, -122.009033)
let annotation1 = MKPointAnnotation()
annotation1.coordinate = coordinate1
annotation1.title = "Annotation 1"
annotation1.subtitle = "Subtitle 1"

let coordinate2 = CLLocationCoordinate2DMake(37.335821492347556, -122.0071341097355)
let annotation2 = MKPointAnnotation()
annotation2.coordinate = coordinate2
annotation2.title = "Annotation 2"
annotation2.subtitle = "Subtitle 2"

mapView.addAnnotation(annotation1)
mapView.addAnnotation(annotation2)

var mapRegion = MKCoordinateRegion()
let mapRegionSpan = 0.02
mapRegion.center = coordinate1
mapRegion.span.latitudeDelta = mapRegionSpan
mapRegion.span.longitudeDelta = mapRegionSpan
mapView.setRegion(mapRegion, animated: true)

let mapViewController = MapViewController()
PlaygroundPage.current.liveView = mapView

还有一张图片来说明问题。

如有任何帮助,我们将不胜感激。谢谢!

我的队友解决了这个问题。这个想法是在选择注释时禁用地图上所有其他注释的用户交互,然后在取消选择注释时 re-enable 它。

func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
    for nearbyAnnotation in mapView.annotations {
        let annotationView = mapView.view(for: nearbyAnnotation)
        if annotationView != nil {
            annotationView!.isUserInteractionEnabled = false
        }
    }
    view.isUserInteractionEnabled = true
}

func mapView(_ mapView: MKMapView, didDeselect _: MKAnnotationView) {
    for nearbyAnnotation in mapView.annotations {
        let annotationView = mapView.view(for: nearbyAnnotation)
        if annotationView != nil {
            annotationView!.isUserInteractionEnabled = true
        }
    }
}