2017-10-25 12 views
0

Mapでinitメソッドを使用してannotationViewsをいくつか追加しました(idによって初期化されています)。今度はナビゲーションバーからクリックボタンで特定のid注釈ビューを更新したいと思います。NavigationBarからクリックボタンで特定のMKAnnotationViewイメージを更新するにはどうすればいいですか?

私はIDを持つ5アノテーションを追加したと仮定(1、2、3、4、および5)VCから

追加されました:初期化AnnotationView

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)の画像を変更したいと思います。

どのように更新できますか?助けてください。 ありがとうございます。

答えて

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") 
     } 
    } 
} 
関連する問題