2017-02-13 33 views
1

我正在嘗試製作很多不同類型的註釋。所有註釋都需要根據美麗的原因進行定製。如何在MKPointAnnotation中設置標識符

我知道它需要使用viewFor註解,但我怎麼知道註釋是什麼樣的?

enter image description here

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) 

    } 

} 
+0

zoneAnnotation.title =「YOURTITLE」 –

+0

您可以使用viewForAnnotation委託,並根據註釋的類型設置標籤。 –

+1

檢查此鏈接 - http://stackoverflow.com/questions/29307173/identify-mkpointannotation-in-mapview –

回答

0

子類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 
} 
相關問題