根据对象类型更改 iOS 上的注释图像

Changing annontation image on iOS depending on object type

我正在尝试根据注释包含的值更改 MKMarkerAnnontationView 的图像。所有注释都使用此代码获得相同的图像,我需要以某种方式根据用户选择的值设置图像。因此,当用户按下另一种类型的停车时,正在使用相同的对象,但使用另一种类型。

我试图强制重新加载注释,但没有成功。有什么建议可以帮助我吗?

if let dequeuedView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier) as? MKMarkerAnnotationView {
            dequeuedView.annotation = annotation
            view = dequeuedView
        } else {

            view = MKMarkerAnnotationView(annotation: annotation, reuseIdentifier: identifier)
            view.canShowCallout = true
            view.glyphTintColor = UIColor.white
            view.calloutOffset = CGPoint(x: -5, y: 5)

            if annotation.type == .bus {
                view.glyphImage = UIImage(named: "bus")
            } else if annotation.type == .disabled {
                view.glyphImage = UIImage(named: "disabled")
            } else if annotation.type == .MC {
                view.glyphImage = UIImage(named: "mc")
            }
        }
        return view
    }
    return nil
}

我遇到了这样的问题,我解决它的唯一方法是从 MKMapView 中删除所有数据点,然后重新添加它们,唯一的区别在于 func mapView(_ mapView: MKMapView, didAdd views: [ MKAnnotationView]) 我正在检查 MKAnnotationView 的标题。 为了实现这一点,我创建了一个 object class 扩展 MKAnnotationView 也有一个标题变量,所以我的注释列表是 classes objects。 当用户更改 MKAnnotation 的图像时,您会更改选择中的标题变量,然后您首先执行

self.sceneView.removeAnnotations(annotations)

然后 re-add 注释点。将被调用的委托函数将像那样

func mapView(_ mapView: MKMapView, didAdd views: [MKAnnotationView]) {
    for view in views{
        if((view.annotation is MKUserLocation) == false){
            // Resize image
            let dt:DataPoint = view.annotation as! DataPoint //Data point is my class
            var pinImage:UIImage!
            if(dt.title = "example"){
                pinImage = exampleImage
                size = CGSize(width: 60, height: 60) //whetever size
            }else{
                pinImage = anotherImage
            }
            UIGraphicsBeginImageContext(size)
            pinImage?.draw(in: CGRect(x:0, y:0, width: size.width, height: size.height))
            let resizedImage = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            view.image = resizedImage
        }
    }
}