1

Tengo una App en donde mando a poner localizaciones con sus respectivos Annotations. Logré cambiar la imagen del pin, pero veo que todas las imágenes son cambiadas.

Lo que me gustaría hacer es mostrar una imagen diferente por cada grupo de localizaciones, por ejemplo, tengo hospitales y farmacias, entonces me gustaría poner una cruz roja en Hospital y una medicina en farmacia.

Por ahora solo tengo las cruces y he estado investigando pero sigo sin éxito. Espero me puedan ayudar.

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
    if annotation is MKUserLocation {
        return nil
    }
    var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: "identifier")
    if annotationView == nil{
        annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: "identifier")
        annotationView!.canShowCallout = true
        annotationView!.rightCalloutAccessoryView = UIButton(type: .detailDisclosure)

        let pinImg = UIImage(named: "curz")
        let size = CGSize(width: 50, height: 50)
        UIGraphicsBeginImageContext(size)
        pinImg!.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
        let resizedImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        annotationView!.image = resizedImage
    }
    else {
        annotationView!.annotation = annotation
    }
    return annotationView
}
7
  • En el código de ejemplo solo estás usando una imagen... ¿En qué casos usarías la otra? el 29 may. 2017 a las 17:38
  • Lo usaría para agregar el otro grupo de anotaciones (otra struct)
    – Daniel C.
    el 29 may. 2017 a las 17:40
  • ¿Y cómo diferencias una annotation de otra? el 29 may. 2017 a las 17:41
  • La verdad no tengo claro ese concepto, soy muy nuevo en Swift. Creo que sería por medio del "identifier"
    – Daniel C.
    el 29 may. 2017 a las 17:43
  • ¿Cómo agregas las annotations al mapa? ¿Ahí puedes diferenciarlas? Tal vez lo que te falte sea crear subclases de MKAnnotation para diferenciar de qué tipo es cada una, y así poder ponerle la imagen que le corresponda... el 29 may. 2017 a las 17:46

1 respuesta 1

2

Lo que podrías hacer es tener una subclase de MKAnnotation donde guardes información que necesitas para poder saber de qué tipo se trata.

Algo así:

enum CustomAnnotationType {
    case hospital
    case farmacia
}

class CustomAnnotation: NSObject, MKAnnotation {
    var coordinate: CLLocationCoordinate2D
    var type: CustomAnnotationType

    init(coordinate: CLLocationCoordinate2D, type: CustomAnnotationType) {
        self.coordinate = coordinate
        self.type = type
    }
}

Cuando agregas las annotations al mapa le dices de qué tipo se trata:

let customAnnotation = CustomAnnotation(coordinate: coord, type: .farmacia)
map.addAnnotation(customAnnotation)

y cuando vas a crear la vista para una annotation determinada, usas la imagen que corresponde para cada una:

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
    if annotation is MKUserLocation {
        return nil
    }
    if let customAnnotation = annotation as? CustomAnnotation {
        let identifier = identifier(forCustomAnnotationType: customAnnotation.type)
        var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: "identifier")
        if annotationView == nil{
            let imageName = imageName(forCustomAnnotationType: customAnnotation.type)
            ...
    }
    ...
}

Nota: identifier(forCustomAnnotationType: ) e imageName(forCustomAnnotationType: ) son funciones que deberías implementar con un switch...

1
  • Agradezco mucho tu ayuda y atención en mi caso :D
    – Daniel C.
    el 29 may. 2017 a las 20:58

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.