Подтвердить что ты не робот

Застрял при использовании MKPinAnnotationView() в Swift и MapKit

У меня есть рабочий цикл для создания аннотаций для элементов заголовка и субтитров для некоторых рабочих точек данных. То, что я хочу сделать в той же структуре цикла, - это установить цвет булавки в фиолетовый, а не по умолчанию. То, что я не могу понять, - это то, что мне нужно сделать, чтобы коснуться MyPapView, чтобы установить штырь соответственно.

Моя рабочая петля и некоторые попытки чего-то...

....
for var index = 0; index < MySupplierData.count; ++index {

  // Establish an Annotation
  myAnnotation = MKPointAnnotation();
  ... establish the coordinate,title, subtitle properties - this all works
  self.theMapView.addAnnotation(myAnnotation)  // this works great.

  // In thinking about PinView and how to set it up I have this...
  myPinView = MKPinAnnotationView();      
  myPinView.animatesDrop = true;
  myPinView.pinColor = MKPinAnnotationColor.Purple;  

  // Now how do I get this view to be used for this particular Annotation in theMapView that I am iterating through??? Somehow I need to marry them or know how to replace these attributes directly without the above code for each data point added to the view
  // It would be nice to have some kind of addPinView.  

}
4b9b3361

Ответ 1

Вам нужно реализовать метод делегата viewForAnnotation и вернуть туда MKAnnotationView (или подкласс).
Это похоже на Objective-C - базовый SDK работает одинаково.

Удалите создание MKPinAnnotationView из цикла for, который добавляет аннотации и реализует метод делегата.

Вот пример реализации метода делегата viewForAnnotation в Swift:

func mapView(mapView: MKMapView!, 
    viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {

    if annotation is MKUserLocation {
        //return nil so map view draws "blue dot" for standard user location
        return nil
    }

    let reuseId = "pin"

    var pinView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId) as? MKPinAnnotationView
    if pinView == nil {
        pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
        pinView!.canShowCallout = true
        pinView!.animatesDrop = true
        pinView!.pinColor = .Purple
    }
    else {
        pinView!.annotation = annotation
    }

    return pinView
}