如何在MapView中更改MKUserLocation注释的displayPriority?

问题描述 投票:2回答:1

我有一个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始终为零,因此未应用我的displayPriority修改。

有什么想法可以更改displayPriority批注视图的MKUserLocation吗?

ios mapkit mapkitannotation
1个回答
0
投票

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

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

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中自定义注释视图:

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以确保它不会隐藏其他注释。

让我知道是否有帮助!

© www.soinside.com 2019 - 2024. All rights reserved.