Z.Q
Z.Q

Reputation: 103

[Swift]How an annotationview always show callout

I want to show the callout of the annotationview always show, I mean when the mapview is loaded, all the annotations‘ callout is shown.

How can I do this?

Upvotes: 2

Views: 2453

Answers (2)

George
George

Reputation: 221

  1. Add annotation on map: mapView.addAnnotation(myAnnotation)
  2. Select annotation mapView.selectAnnotation(myAnnotation, animated: false)
  3. Add private function private func bringMyAnnotationToFront() with code if let myAnnotation = mapView.annotations.first(where: { $0 is MKPointAnnotation }) { mapview.selectAnnotation(myAnnotation, animated: false) }
  4. Set MKMapViewDelegate and implement two methods with bringMyAnnotationToFront: func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView), func mapView(MKMapView, didDeselect: MKAnnotationView)

Upvotes: 1

AamirR
AamirR

Reputation: 12198

At anytime, there can be only one callout on the map. Framework reuses the previous callout when a new is to be presented, and here is showing a single callout view when annotation is added, like so

let annotation = MKPointAnnotation()
annotation.title = "Title for Callout"
mapView.addAnnotation(annotation)

This causes the delegate method viewForAnnotation to be fired:

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
    let view = MKAnnotationView(annotation: annotation, reuseIdentifier: "AnnotId")
    view.canShowCallout = true
    return view
}

Framework will add the above returned view and the didAddViews delegate is fired, now show the callout view by selecting the annnotation, like so

func mapView(_ mapView: MKMapView, didAdd views: [MKAnnotationView]) {
    if let annotation = views.first(where: { $0.reuseIdentifier == "AnnotId" })?.annotation {
        mapView.selectAnnotation(annotation, animated: true)
    }
}

Upvotes: 3

Related Questions