Stuck on using MKPinAnnotationView() within Swift and MapKit

后端 未结 1 843
自闭症患者
自闭症患者 2020-12-06 01:38

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

相关标签:
1条回答
  • 2020-12-06 01:57

    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
    }
    
    0 讨论(0)
提交回复
热议问题