在选择器swift中发送对象

时间:2017-09-21 20:04:09

标签: ios swift selector

可以通过点击按钮发送多个对象吗?

我正在尝试调用此函数

 func getWeatherResults (lat: Double, long: Double{

}

单击在viewFor上创建的按钮,从单击的注释中获取坐标

 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
}

谢谢!

2 个答案:

答案 0 :(得分:1)

您可以为按钮创建自定义类。像这样:

class customButton: UIButton {
    var parameter : String?
}

将按钮的类型设置为customButton并设置参数:

button.parameter = ""

答案 1 :(得分:1)

您无法自定义发送到按钮操作的参数。唯一有效的选项(如UIControl文档中所述)包括参数,发件人(本例中为按钮)或发件人和事件。

正确的解决方案是将坐标存储在属性中。然后,您可以根据需要在按钮处理程序中访问该属性。

将属性添加到您的班级:

var lastCoordinate: CLLocationCoordinate2D?

更新地图视图委托方法:

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

    // and the rest of the code
}

并更新您的getWeather方法:

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