我正在尝试在MKAnnotationView中显示图像。图像最初正在加载,但是当我尝试在按钮上更改一些图像时,单击图像并没有改变,而是重叠了。下面是我使用的代码。
MapView委托
extension MapViewController: MKMapViewDelegate {
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if annotation is MKUserLocation {
return nil
}
var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: "MapAnnotation") as? MapAnnotationView
if annotationView != nil {
annotationView?.annotation = annotation
}
else {
annotationView = MapAnnotationView(annotation: annotation, reuseIdentifier: "MapAnnotation")
}
annotationView?.canShowCallout = true
return annotationView
}
MKAnnotationView
class MapAnnotationView: MKAnnotationView {
// Required for MKAnnotationView
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(annotation: MKAnnotation?, reuseIdentifier: String?) {
super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)
//super.prepareForReuse()
guard let attractionAnnotation = self.annotation as? MapAnnotation else { return }
if attractionAnnotation.type == PinType.hospital {
image = UIImage.init(named: "hospital_green")
}
}
按钮操作
@IBAction func btnGreen_Click(_ sender: Any) {
for annotation in (policyMapView?.annotations)! {
let mapAnnotationView = policyMapView?.view(for: annotation) as? AssistMapAnnotationView
//if !(mapAnnotationView?.annotation is MKUserLocation) {
if !(mapAnnotationView?.annotation is MKUserLocation) {
let mapAnnotation = annotation as? AssistMapAnnotation
if mapAnnotation?.type == PinType.hospital {
if (mapAnnotation?.insurer_id == selectedInsurer1) {
mapAnnotationView?.image = UIImage.init(named: "hospital_purple")
}else{
mapAnnotationView?.image = UIImage.init(named: "hospital_green")
}
}
} else {
}
}
}
}