我需要从Firebase中按值使用不同颜色的注释,所以我创建了一个类:
class AnnotationClass : MKPointAnnotation {
var parametro: String?
var titolo:String?
var sottotitolo: String?
var tipo: String?
}
然后设置它:
let annotation = AnnotationClass()
annotation.titolo = location.citta?.uppercased() as? String
annotation.sottotitolo = "\(location.titolo!) POSTI"
annotation.parametro = "\(location.id!)"
annotation.tipo = "\(location.tipo!)"
annotation.title = "\(location.tipo!)"
这里的主要内容是如何在下一个函数中获取它?如果commentView?.annotation?.tipo ==“ CONCORSO” 错误:“ MKAnnotation”类型的值没有成员“ tipo”
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
var annotationView: MKMarkerAnnotationView? = mapView.dequeueReusableAnnotationView(withIdentifier: "mia2") as? MKMarkerAnnotationView
annotationView = MKMarkerAnnotationView(annotation: annotation, reuseIdentifier: "mia2")
if annotationView?.annotation?.tipo == "CONCORSO" {
annotationView?.markerTintColor = #colorLiteral(red: 0.2392156869, green: 0.6745098233, blue: 0.9686274529, alpha: 1)
annotationView?.glyphText = "C"
} else {
annotationView?.markerTintColor = #colorLiteral(red: 0.9254901961, green: 0.2352941176, blue: 0.1019607843, alpha: 1)
annotationView?.glyphText = "A"
}
return annotationView
}
答案 0 :(得分:0)
您需要将annotation: MKAnnotation
强制转换为自定义类:
let myCustomAnnotation = annotation as? AnnotationClass
以下,我已修复了您的委托方法中的多个问题
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
var annotationView: MKMarkerAnnotationView! = mapView.dequeueReusableAnnotationView(withIdentifier: "mia2") as? MKMarkerAnnotationView
if (annotationView == nil) {
// Create a new annotation view
annotationView = MKMarkerAnnotationView(annotation: annotation, reuseIdentifier: "mia2")
} else {
// update existing (reusable) annotationView's annotation
annotationView.annotation = annotation
}
if let myCustomAnnotation = annotation as? AnnotationClass, myCustomAnnotation.tipo == "CONCORSO" {
annotationView.markerTintColor = #colorLiteral(red: 0.2392156869, green: 0.6745098233, blue: 0.9686274529, alpha: 1)
annotationView.glyphText = "C"
} else {
annotationView.markerTintColor = #colorLiteral(red: 0.9254901961, green: 0.2352941176, blue: 0.1019607843, alpha: 1)
annotationView.glyphText = "A"
}
return annotationView
}
您还可以将if语句缩短为:
if (annotation as? AnnotationClass)?.tipo == "CONCORSO" {
...
}