如何使用 MKAnnotation 存储属性

How to store an attribute with a MKAnnotation

我正在使用这条线创建带有自定义图钉的地图

self.mapView.addAnnotation(customMapAnnotationView.annotation!)

但稍后我需要遍历所有引脚并将它们与一个密钥匹配,该密钥将确定是否要删除它们。

for annotation:ChatRoomMapAnnotationView in self.chatMapView.annotations {
 ...
}

如何将此密钥与注释一起存储以便在我迭代时可用?

谢谢

如果我理解正确,如果你想在注释中存储额外的信息,你需要创建一个符合 MKAnnotation 的 class,就像这样

class ChatRoomMapAnnotationView: NSObject, MKAnnotation {

let myKeyIdentifier: String
let coordinate: CLLocationCoordinate2D
let title: String?
let subtitle: String?

init(myKeyIdentifier: String, coordinate: CLLocationCoordinate2D, title: String?=nil, subtitle: String?=nil ) {
    self.myKeyIdentifier = myKeyIdentifier
    self.coordinate = coordinate
    self.title = title
    self.subtitle = subtitle
}
}

self.mapView.addAnnotation(CustomMapAnnotationView(.....))

for annotation in self.chatMapView.annotations {
    if let chatAnnotation = annotation as? ChatRoomMapAnnotationView {
       if chatAnnotation.myKeyIdentifier == "specialKey" {
          // do something special
       }
    }
}

您需要自定义 class 注释:

class CustomPin: MKPointAnnotation {
   var yourVar1: yourType1
   var yourVar2: yourType2
   // ...
   var yourVar3: yourType3
}

那么你可以这样使用它:

if annotation is CustomPin {
     // do something
}

希望对您有所帮助