我有一个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
吗?
我花了数小时试图通过自定义默认用户位置注释来解决此问题,但无济于事。
相反,作为一种解决方法,我制作了自己的位置标记并隐藏了默认位置注释。这是我的代码:
向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
以确保它不会隐藏其他注释。
让我知道是否有帮助!