我正在尝试进行很多不同类型的注释。出于美观原因,所有注释都需要自定义。
我知道它需要使用viewFor Annotation,但是我怎么知道哪种注释?
func addZoneAnnotation() {
let zoneLocations = ZoneData.fetchZoneLocation(inManageobjectcontext: managedObjectContext!)
for zoneLocation in zoneLocations! {
let zoneCoordinate: CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: Double(zoneLocation["latitude"]!)!, longitude: Double(zoneLocation["longitude"]!)!)
let zoneAnnotation = MKPointAnnotation()
zoneAnnotation.coordinate = zoneCoordinate
map.addAnnotation(zoneAnnotation)
}
}
最佳答案
子类MKPointAnnotation
添加所需的任何属性:
class MyPointAnnotation : MKPointAnnotation {
var identifier: String?
}
然后,您可以按以下方式使用它:
func addZoneAnnotation() {
let zoneLocations = ZoneData.fetchZoneLocation(inManageobjectcontext: managedObjectContext!)
for zoneLocation in zoneLocations! {
let zoneCoordinate: CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: Double(zoneLocation["latitude"]!)!, longitude: Double(zoneLocation["longitude"]!)!)
let zoneAnnotation = MyPointAnnotation()
zoneAnnotation.coordinate = zoneCoordinate
zoneAnnotation.identifier = "an identifier"
map.addAnnotation(zoneAnnotation)
}
}
最后,当您需要访问它时:
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
guard let annotation = annotation as? MyPointAnnotation else {
return nil
}
var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: "reuseIdentifier")
if annotationView == nil {
annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: "reuseIdentifier")
} else {
annotationView?.annotation = annotation
}
// Now you can identify your point annotation
if annotation.identifier == "an identifier" {
// do something
}
return annotationView
}
关于ios - 如何在MKPointAnnotation中设置标识符,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42202607/