0

How to pass a "coordinates" variable to a function: didClickDetailDisclosure ?


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

 let rightButton = UIButton(type: .detailDisclosure)
        let coordinates = annotation.coordinate
        rightButton.
        rightButton.addTarget(self, action: #selector(didClickDetailDisclosure(button:)), for: .touchUpInside)
                   annotationView?.rightCalloutAccessoryView = rightButton

@objc func didClickDetailDisclosure(button: UIButton) {

           performSegue(withIdentifier: "SegueAddFromMaps", sender: self)
}

Thanks for help!

prem111
  • 63
  • 1
  • 7

2 Answers2

0

When sending parameters via target/action using an @objC function, the function has to take a certain form.

Basically, it has to send the "Sender" or the item itself as the parameter. In your case, it is sending the button as the parameter because the target is added to the button.

So if you want to pass the coordinates as a parameter, you can create a custom button class that stores Coordinates variables, and pass that custom button via your didClickDetailDisclosure method. You can make your rightButton a custom button: Passing arguments to selector in Swift

class CustomButton : UIButton {

    var coordinate: CLLocationCoordinate2D?

    convenience init(coordinate: CLLocationCoordinate2D, object: Any) {
        self.init()
        self.coordinate = coordinate
    }
}

@objc func didClickDetailDisclosure(button: CustomButton) {

          let coordinate = button.coordinate
           performSegue(withIdentifier: "SegueAddFromMaps", sender: self)
}
PatPatchPatrick
  • 380
  • 1
  • 12
0

If the variable you are passing is Int type, you can set a tag on the button.

rightButton.tag = variable

and you can access it in the function like

@objc func didClickDetailDisclosure(button: UIButton) {
       let variable = button.tag
}
Kevin Lee
  • 195
  • 2
  • 9