First, it's worth noting that the standard UX is to present a callout bubble which shows the user enough information to confirm that this was the intended annotation view and then have the callout include left and/or right accessory views (e.g. buttons on left and/or right side of the callout) which lets the user then perform some additional task(s) using that annotation. See Creating Callouts in the Location and Maps Programming Guide.
But if you want to immediately do something else when the user taps on the annotation, then set up your annotation view so that (a) it has no callout; and then (b) implement MKMapViewDelegate
method didSelectAnnotationView
to perform whatever task you want when the user taps on the annotation view.
For example, assuming you've specified the delegate
for your map view, you could do something like the following in Swift 3/4:
private let reuseIdentifier = "MyIdentifier"
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if annotation is MKUserLocation { return nil }
var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseIdentifier) as? MKPinAnnotationView
if annotationView == nil {
annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseIdentifier)
annotationView?.tintColor = .green // do whatever customization you want
annotationView?.canShowCallout = false // but turn off callout
} else {
annotationView?.annotation = annotation
}
return annotationView
}
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
// do something
}
Or in Swift 2:
func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
if annotation is MKUserLocation { return nil }
var annotationView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseIdentifier) as? MKPinAnnotationView
if annotationView == nil {
annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseIdentifier)
annotationView?.tintColor = UIColor.greenColor() // do whatever customization you want
annotationView?.canShowCallout = false // but turn off callout
} else {
annotationView?.annotation = annotation
}
return annotationView
}
func mapView(mapView: MKMapView, didSelectAnnotationView view: MKAnnotationView) {
// do something
}