Pablo R.
Pablo R.

Reputation: 723

send objects in selector swift

can you send multiple objects by clicking a button?

I am trying to call this function

 func getWeatherResults (lat: Double, long: Double{

}

by clicking a button created on viewFor to get coordinates from the annotation clicked

 func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {

    var **lat** = annotation.coordinate.latitude
    var **long** = annotation.coordinate.latitude

    guard !(annotation is MKUserLocation) else { return nil }

    let annotationIdentifier = "Identifier"
    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

        let smallSize = CGSize(width: 30, height: 30)

        let krakenPinImg = UIImage(named: "kraken_ic")
        annotationView.image = krakenPinImg?.resizedImageWithinRect(rectSize: CGSize(width: 30, height: 30))

        let button = UIButton(frame: CGRect(origin: CGPoint.zero, size: smallSize))
        button.setBackgroundImage(UIImage(named: "weatherWindyDarkGray"), for: UIControlState())
        button.addTarget(self, action: #selector(getWeatherResults) for: .touchUpInside)
        annotationView.leftCalloutAccessoryView = button
    }


    return annotationView
}

thanks!

Upvotes: 0

Views: 347

Answers (2)

rmaddy
rmaddy

Reputation: 318804

You can't customize the parameters sent to a button's action. The only valid options (as covered in the documentation for UIControl) are to have parameters, the sender (the button in this case), or the sender and the event.

The proper solution is to store the coordinate in a property. Then you can access that property in the button handler as needed.

Add the property to your class:

var lastCoordinate: CLLocationCoordinate2D?

Update your map view delegate method:

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
    lastCoordinate = annotation.coordinate

    // and the rest of the code
}

And update your getWeather method:

func getWeatherResults() {
    if let lastCoordinate = lastCoordinate {
        let lat = lastCoordinate.latitude
        let lon = lastCoordinate.longitude
        // Use these values as needed
    }
}

Upvotes: 1

user7021134
user7021134

Reputation:

You can create a custom class for your button. Like this:

class customButton: UIButton {
    var parameter : String?
}

Set type of your button as customButton and set the parameter:

button.parameter = ""

Upvotes: 1

Related Questions