如何更改显示地图视图中MKUser位置注释的优先级?



>我有一个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修改。

知道如何更改MKUserLocation注释视图的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中自定义注释视图:

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

让我知道这是否有帮助!

如果有人仍在为此苦苦挣扎,您可以使用func mapView(_ mapView: MKMapView, didAdd views: [MKAnnotationView])来执行此操作:

// MARK: - MKMapViewDelegate
func mapView(_ mapView: MKMapView, didAdd views: [MKAnnotationView]) {
for view in views {
if view.annotation is MKUserLocation {
view.displayPriority = .defaultLow
break
}
}
}

这样,您仍然可以使用系统提供的视图进行MKUserLocation,而无需手动构建自己的视图。

最新更新