ios - 如何在 MKPointAnnotation 中设置标识符
<p><p>我正在尝试制作很多不同类型的注释。出于美观的原因,所有注释都需要自定义。</p>
<p>我知道它需要使用viewFor Annotation,但是我怎么知道是什么注解呢?</p>
<p> <a href="/image/xI0UV.png" rel="noreferrer noopener nofollow"><img src="/image/xI0UV.png" alt="enter image description here"/></a> </p>
<pre><code>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)
}
}
</code></pre></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>子类 <code>MKPointAnnotation</code> 以添加您想要的任何属性:</p>
<pre><code>class MyPointAnnotation : MKPointAnnotation {
var identifier: String?
}
</code></pre>
<p>那么你可以如下使用它:</p>
<pre><code>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)
}
}
</code></pre>
<p>最后当你需要访问它时:</p>
<pre><code>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
}
</code></pre></p>
<p style="font-size: 20px;">关于ios - 如何在 MKPointAnnotation 中设置标识符,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/42202607/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/42202607/
</a>
</p>
页:
[1]