ios - 在选择器中快速发送对象

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

谢谢!

最佳答案

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

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

将属性添加到您的类中:

var lastCoordinate: CLLocationCoordinate2D?

更新您的 map View 委托(delegate)方法:

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

关于ios - 在选择器中快速发送对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46352349/

相关文章:

ios - 使用 UIView 动画旋转 UIImageView 360 度?

ios - 向ios NSString中的某些文本添加点击事件

ios - 如何使用 os_log 在控制台应用程序中查看 iOS 设备日志

ios - 在没有 Segues 的 ViewController 之间传输数据 - Swift

redux - react native中的mapStateToProps、mapDispatchToProps类型和选择器有什么区别

html - sIFR 3 - 选择器

ios - 我在 tableview 上显示的代码中的错误在哪里?

ios - Swift:从 AppDelegate 中的 UNTextInputNotificationAction 获取内容

ios - 验证失败后刷新(重新加载)NSManagedObject

objective-c - 为什么在 Objective-C 中允许 [object.delegate self]?