如何在 NavigationBar 的单击按钮上更新任何特定的 MKAnnotationView 图像?

How to update any specific MKAnnotationView image on click button from NavigationBar?

我在地图上添加了一些 annotationViews 和 init 方法(由那里的 id 初始化)。现在我想在导航栏的点击按钮上更新特定的 id 注释视图。

假设我添加了 5 个 id 为(1、2、3、4 和 5)的注释

添加自 VC:

let annotation = MapPinAnnotation(title: storeItem.name!, location: CLLocationCoordinate2DMake(Double(lat), Double(long)), id: storeItem.storeId!)
self.mapview.addAnnotation(annotation)

已初始化注释视图:

class MapPinAnnotation: NSObject, MKAnnotation {

    var title:String?
    var id:String?
    private(set) var coordinate = CLLocationCoordinate2D()

    init(title newTitle: String, location: CLLocationCoordinate2D, id: String) {
        super.init()

        self.title = newTitle
        self.coordinate = location
        self.id = id
    }
}

ViewFor注解方法:

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
        if (annotation is MKUserLocation) {
            return nil
        }
        if (annotation is MapPinAnnotation) {
            let pinLocation = annotation as? MapPinAnnotation
            // Try to dequeue an existing pin view first.
            var annotationView: MKAnnotationView? = mapView.dequeueReusableAnnotationView(withIdentifier: "MapPinAnnotationView")
            if annotationView == nil {
                annotationView?.image = UIImage(named: Constants.Assets.PinGreen)
            }
            else {
                annotationView?.annotation = annotation
            }
            return annotationView
        }
        return nil
    }

现在我想在导航栏中单击按钮时更改注释视图 (id 4) 的图像。

如何更新?请帮忙。 提前致谢。

您可以通过view(for: )方法获取特定的MKAnnotationView。试试下面的代码:

func clickButton() {
    for annotation in self.mapView.annotations {
        if annotation.id == 4 {
            let annotationView = self.mapView.view(for: annotation)
            annotationView?.image = UIImage(named: "Image name here")
        }
    }
}