在选择器 swift 中发送对象

send objects in selector swift

您可以通过单击一个按钮来发送多个对象吗?

我正在尝试调用这个函数

 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
}

谢谢!

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

class customButton: UIButton {
    var parameter : String?
}

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

button.parameter = ""

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

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

将 属性 添加到您的 class:

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
    }
}