Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
262 views
in Technique[技术] by (71.8m points)

ios - Stuck on using MKPinAnnotationView() within Swift and MapKit

I have a working loop to setup annotations for the title and subtitle elements for some working data points. What I want to do within that same loop structure is to set the pin color to Purple instead of the default. What I can't figure out is what I need to do to tap into my theMapView to set the pin accordingly.

My working loop and some attempts at something...

....
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.  

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to implement the viewForAnnotation delegate method and return an MKAnnotationView (or subclass) from there.
This is just like in Objective-C -- the underlying SDK works the same way.

Remove the creation of MKPinAnnotationView from the for loop that adds the annotations and implement the delegate method instead.

Here is a sample implementation of the viewForAnnotation delegate method in 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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...