pavlos
pavlos

Reputation: 567

Adding onClick event to MKAnnotation swift

I am currently getting some locations from a web request using alamofire, store them in my Object array and then display them on a MKMapView.

 func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
    guard !(annotation is MKUserLocation) else {
        return nil
    }

    let annotationIdentifier = "AnnotationIdentifier"

    var annotationView: MKAnnotationView?
    if let dequeuedAnnotationView = mapView.dequeueReusableAnnotationView(withIdentifier: annotationIdentifier) {
        annotationView = dequeuedAnnotationView
        annotationView?.annotation = annotation
    }
    else {
        annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: annotationIdentifier)
        annotationView?.rightCalloutAccessoryView = UIButton(type: .detailDisclosure)
    }

    if let annotationView = annotationView {
        annotationView.canShowCallout = true
        annotationView.image = UIImage(named: "atm_map_icon")
    }

    return annotationView
}

And here is where i parse the json, put the result in an array and the loop through the array and add the markers to the map

for var i in 0..<json.count{
                let name = json[i]["Name"].string
                let address = json[i]["Address"].string
                let lat = json[i]["Lat"].double
                let lon = json[i]["Lon"].double
                let atm = Atm(name: name!,address: address!,lat: lat!,lon: lon!)
                self.atmArrayList.append(atm)



            }
            print(self.atmArrayList.count)
        }
        for atm in self.atmArrayList{
            let atmPin = AtmAnnotation(title: atm.name!, subtitle: atm.address!, atm: atm, coordinate: CLLocationCoordinate2D(latitude: atm.lat!, longitude: atm.lon!))
            self.annotationArray.append(atmPin)
        }

        self.atmMapView.addAnnotations(self.annotationArray)

What i want to achieve is so when the user clicks on the rightCalloutAccessoryView button, i want to pass the specific Atm object of that Annotation to the another ViewController.

My guess is to give the Annotations an id and then get the Atm from the Atm array in that specific position??

Upvotes: 0

Views: 3406

Answers (1)

Reinier Melian
Reinier Melian

Reputation: 20804

You need to implement this method of MapViewDelegate in your viewController

func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
  let anotherViewController = self.storyboard?.instantiateViewController(withIdentifier: "anotherViewController") as! AnotherViewController
  if let atmPin = view.annotation as? AtmAnnotation
  {
    anotherViewController.currentAtmPin = atmPin
  }
  self.navigationController?.pushViewController(anotherViewController, animated: true)

}

Hope this helps

Upvotes: 2

Related Questions