Swift,如何使用 MKPointAnnotation 为每个放置的图钉存储自定义值?

Swift, how can I store a custom value for each dropped pin using MKPointAnnotation?

我希望能够使用 MKPointAnnotation 为每个掉落的图钉存储自定义值。具体来说,我想用每个 pin 存储一些 id 并在 calloutAccesoryControlTapped.

检索

您必须使用 属性 对 MKPointAnnotation 进行子类化以存储此自定义值(我将其命名为标签)

import UIKit
import MapKit
class CustomPointAnnotation: MKPointAnnotation {
    var tag: Int!
}

创建图钉:

let annotation = CustomPointAnnotation()
annotation.coordinate = CLLocationCoordinate2D(latitude: CLLocationDegrees(latitude), longitude: CLLocationDegrees(longitude))
            annotation.title = [insert name]
            annotation.tag = [insert tag]
            self.mapView.addAnnotation(annotation)

并且在您的 mapView 委托的 viewForAnnotation 中,在检查 dequeableAnnotation 之后,您执行以下操作:

  if (annotation is CustomPointAnnotation) {
       pinView?.tag = (annotation as! CustomPointAnnotation).tag
  }

对 Marcos Griselli 的 进行了细微编辑。需要转换pinView才能访问自定义标签。

if (annotation is CustomPointAnnotation) {
    (pinView?.annotation as! CustomPointAnnotation).tag = (annotation as! CustomPointAnnotation).tag
}