iosfan iosfan - 2 months ago 29
Swift Question

MapKit annotation how to add detail disclosure info button?

I am putting

annotation
on a map and after clicking the pin, there should be a
detail disclosure info button
on the right side, so I can add more code after tapping the button. But when I run the project, clicking on the pin, there is no
info button
shows up. Can anyone help to find problem of my code?

I am expecting an info button on the right: enter image description here

My Code:

extension ViewController: MKMapView{


func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
if let annotation = annotation as? Artwork {
let identifier = "pin"
var view: MKPinAnnotationView
if let dequeuedView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier)
as? MKPinAnnotationView {
dequeuedView.annotation = annotation
view = dequeuedView
} else {

view = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)
view.canShowCallout = true
view.calloutOffset = CGPoint(x: -5, y: 5)
view.rightCalloutAccessoryView = UIButton(type:.detailDisclosure) as UIView
}
return view
}
return nil
}

}

Answer

Create a MKAnnotationView and add a button to it. So:

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
    let annotationView = MKPinAnnotationView(annotation:annotation, reuseIdentifier:"")
    annotationView.isEnabled = true
    annotationView.canShowCallout = true

    let btn = UIButton(type: .detailDisclosure)
    annotationView.rightCalloutAccessoryView = btn
    return annotationView
}

dequeueReusableAnnotationView example:

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
        let annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: "")
        annotationView?.isEnabled = true
        annotationView?.canShowCallout = true

        let btn = UIButton(type: .detailDisclosure)
        annotationView?.rightCalloutAccessoryView = btn
        return annotationView
    }
Comments