Providing Detailed Pin Information with Custom Views - Maps and Location - iOS 9 Swift Programming Cookbook (2015)

iOS 9 Swift Programming Cookbook (2015)

Chapter 8. Maps and Location

8.4 Providing Detailed Pin Information with Custom Views

Problem

When the user taps on an annotation in a map, you want to display details for that annotation in a view.

Solution

Set the detailCalloutAccessoryView property of your MKAnnotationView instances to a valid UIView instance.

Discussion

Create your project just as you did in Recipe 8.3. In this recipe, I am going to reuse a lot of code from the aforementioned recipe, except for the implementation of the mapView(_:viewForAnnotation:) delegate method of our view controller. Instead, we are going to construct instances here of MKAnnotationView and then set the detail callout accessory view:

func mapView(mapView: MKMapView,

viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {

let view: MKAnnotationView

if let v = mapView

.dequeueReusableAnnotationViewWithIdentifier(identifier){

//reuse

view = v

} else {

//create a new one

view = MKAnnotationView(annotation: annotation,

reuseIdentifier: identifier)

view.canShowCallout = true

if let img = UIImage(named: "Icon"){

view.detailCalloutAccessoryView = UIImageView(image: img)

}

if let extIcon = UIImage(named: "ExtIcon"){

view.image = extIcon

}

}

return view

}

Figure 8-3 shows The image of an annotation on a map. The image inside the callout is the detail callout accessory view.

Figure 8-3. Annotation with detail callout accessory

NOTE

I am using two public domain images in this recipe. You also can find public domain images on Google.

See Also