#mkannotation
#mkannotation
Вопрос:
Мне нужна аннотация с другим цветом по значению из 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!)"
простое число здесь, как его получить в следующей функции? если annotationView?.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
}
Ответ №1:
Вам нужно привести 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" {
...
}