swift - 通过 rightCalloutAccessoryView 访问自定义 MKAnnotation 数据时出现问题

标签 swift mapkit

当由 rightCalloutAccessoryView 触发时,我正在尝试访问我在自定义注释数据中设置的一些自定义数据。我收到如下所述的编译器错误。这是我的自定义 MKAnnotation,带有几个额外的变量 - status 和 supplierdataindex

class CustomMapPinAnnotation : NSObject, MKAnnotation {
  var coordinate: CLLocationCoordinate2D
  var title: String
  var subtitle: String
  var status: Int             
  var supplierdataindex: Int  

  init(coordinate: CLLocationCoordinate2D, title: String, subtitle: String, status: Int, supplierdataindex: Int) {
    self.coordinate = coordinate
    self.title = title
    self.subtitle = subtitle
    self.status = status
    self.supplierdataindex = supplierdataindex     
  }
}  // CustomMapPinAnnotation

var myCustomMapPinAnnotationArray = [CustomMapPinAnnotation] ()
// I build an array and put that into myCustomMapPinAnnotationArray
...
// I add the annotations initially in viewDidLoad in the ViewController.swift via this call  
theMapView.addAnnotations(myCustomMapPinAnnotationArray)

就 map 和图钉而言,一切都很好,但现在我想访问 myCustomMapPinAnnotation 数组的自定义部分,特别是“状态”和“供应商数据索引” 这将插入更详细 View 的决策。我正在使用 calloutAccessoryControlTapped 来捕捉点击。

问题是这个编译器在下面给我一个错误,我尝试设置访问权限,我认为这会让我指向我认为应该内置到注释数据中的自定义数据。

“MKAnnotation”不能转换为“CustomMapPinAnnotation”

func mapView(mapView: MKMapView!, annotationView: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {

    if control == annotationView.rightCalloutAccessoryView {
        // This works and prints the data
        println("Right Callout was pressed and title = \(annotationView.annotation.title)")

        // This line yields a compiler error of: 'MKAnnotation is not convertible to 'CustomMapPinAnnotation'
        var pinannotation : CustomMapPinAnnotation = annotationView.annotation

        println("status was = \(myannotation.status)")
        println("supplierdataindex was = \(myannotation.supplierdataindex)")     
    }
}

最佳答案

您必须像这样将其类型转换为 CustomMapPinAnnotation,

func mapView(mapView: MKMapView!, annotationView: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {

    if control == annotationView.rightCalloutAccessoryView {

        if let pinannotation = annotationView.annotation as? CustomMapPinAnnotation{

          println("status was = \(pinannotation.status)")
          println("supplierdataindex was = \(pinannotation.supplierdataindex)")    

       }
    }
}

关于swift - 通过 rightCalloutAccessoryView 访问自定义 MKAnnotation 数据时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25967783/

相关文章:

ios - 核心数据类的全局变量(坏?好?)

ios - 更改不同位置的 map 图钉颜色

iphone - 在ios应用程序中添加 map 按钮

Swift,包含整数的数组文字可以与整数数组互换使用吗?

ios - 有更好的方法吗?

swift - 我如何确定一个正方形是否可以在不与其他 Sprite 接触的情况下到达位置?

ios - MKMapView display showsScale distance in km (not mi)

ios - 如何通过传递地址打开 Apple Maps 行车路线

iphone - 在 map 上显示用户位置并停止位置

swift - 如何在 Swift 中永远重复动画(HUGE_VALF)?