Show Annotation Title and SubTitle in Custom MKPin

2019-09-10 11:29发布

问题:

I am using MKPinAnnotationView inside my App.

I am setting MapView object as delegate, and using this code for customising my AnnotationView

   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!.image = UIImage(named:"store.jpg")
            pinView!.animatesDrop = true
            pinView!.pinTintColor = UIColor.darkGrayColor()
         }
        else {
            pinView!.annotation = annotation
        }

        return pinView
    }

I am getting custom AnnotationView as I required.However, I am missing the features of title and subtitle of MKPointAnnotation.

I wish to see title and subtitle for the grey dots.

回答1:

I was overriding one func

func mapView(mapView: MKMapView, didSelectAnnotationView view: MKAnnotationView) {
        mapView.deselectAnnotation(view.annotation, animated: true)
    }

I commented this function out and got the titles and subtitles.

Updated Code

/*
 func mapView(mapView: MKMapView, didSelectAnnotationView view: MKAnnotationView) {
 mapView.deselectAnnotation(view.annotation, animated: true)
 }
 */
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"
    let  pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
    pinView.canShowCallout = true
    pinView.animatesDrop = true
    pinView.pinTintColor = UIColor.darkGrayColor()
    pinView.draggable = true
    pinView.accessibilityLabel = "hello"
    let btn = UIButton(type: .DetailDisclosure)
    pinView.rightCalloutAccessoryView = btn
    return pinView
}