如何在导航栏中单击按钮时更新任何特定的 MKAnnotationView 图像?

Asi*_*aza 1 mapkit mkannotationview swift3

我使用 init 方法在 Map 添加了一些注释视图(由 id 初始化)。现在我想更新导航栏中单击按钮上的特定 id 注释视图。

假设我添加了 5 个带有 ids 的注释(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)
Run Code Online (Sandbox Code Playgroud)

初始化的AnnotationView:

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
    }
}
Run Code Online (Sandbox Code Playgroud)

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
    }
Run Code Online (Sandbox Code Playgroud)

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

我怎样才能更新?请帮忙。提前致谢。

Kos*_*awa 5

您可以使用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")
        }
    }
}
Run Code Online (Sandbox Code Playgroud)