如何通过NavigationBar点击按钮更新任何特定的MKAnnotationView图像?

时间:2017-10-25 03:59:24

标签: swift3 mapkit mkannotationview

我在Map中使用init方法添加了一些annotationViews(由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)

初始化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
    }
}

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)的图像。

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

1 个答案:

答案 0 :(得分:1)

您可以使用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")
        }
    }
}