ios - 如何更改 MapView 中 MKUserLocation 注释的显示优先级?

标签 ios mapkit mapkitannotation

我有一个 MapView 显示一些带有 displayPriority = .defaultHight 的注释以允许自动聚类。

MapView 还显示当前用户位置,默认显示优先级为required

这会导致我的注释在非常接近时被用户位置注释隐藏。

我想通过将用户位置注释的显示优先级设置为 defaultLow 来更改此行为。

我试过使用这种方法:

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
    if annotation is MKUserLocation {
        let userView = mapView.view(for: annotation)
        userView?.displayPriority = .defaultLow
        return userView
    }
    return mapView.view(for: annotation)
}

但是 userView 始终为 nil,因此我的 displayPriority 修改未应用。

知道如何更改 MKUserLocation 注释 View 的 displayPriority 吗?

最佳答案

我花了几个小时试图通过自定义默认用户位置注释来解决这个问题,但无济于事。

相反,作为一种解决方法,我制作了自己的位置标记并隐藏了默认位置注释。这是我的代码:

将注释变量添加到您的 viewController:

private var userLocation: MKPointAnnotation?

在您的 viewDidLoad 中,隐藏默认位置标记:

mapView.showsUserLocation = false

更新 didUpdateLocations 中的位置:

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let userLocation = locations.first else { return }
        if self.userLocation == nil {
            let location = MKPointAnnotation()
            location.title = "My Location"
            location.coordinate = userLocation.coordinate
            mapView.addAnnotation(location)
            self.userLocation = location
        } else {
            self.userLocation?.coordinate = userLocation.coordinate
        }
    }

然后在viewFor annotation中自定义注解 View :

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
            // user location annotation
            let identifier = "userLocation"
            var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier)

            if annotationView == nil {
                annotationView = MKMarkerAnnotationView(annotation: annotation, reuseIdentifier: identifier)
                (annotationView as? MKMarkerAnnotationView)?.markerTintColor = .blue
                annotationView?.canShowCallout = true
            } else {
                annotationView?.annotation = annotation
            }
            annotationView?.displayPriority = .defaultLow
            return annotationView
}

我将注释的 displayPriority 更改为 .defaultLow 以确保它不会隐藏其他注释。

如果这有帮助,请告诉我!

关于ios - 如何更改 MapView 中 MKUserLocation 注释的显示优先级?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57543273/

相关文章:

ios - UIDocumentInteractionController 导航栏颜色

ios - 发送按钮不发送

ios - 如何在 map View 中拖动注释图钉?

ios - 选择注释 View 时指定方法

iOS 临时分发 OTA : Bundle version in plist

ios - 限制 MapView 上的重复注释

Swift MapKit 不显示固定方向

ios - Mapkit 标注附件按钮激活

swift - 为什么我的注释标注不会出现?仅当使用自定义图像作为图钉时,标注才有效

ios:添加注释并调用 mapView.showAnnotations() 后禁用 mapView 更新