2015-09-29 17 views
15

Sto provando a passare da Swift 1.2 a Swift 2.0 e sono alla fine delle modifiche. Attualmente sto apportando delle modifiche a MapViewController e non ci sono errori o avvertenze, ma l'immagine personalizzata per il mio pin (annotationView) non è assegnata al pin e mostra quella predefinita (punto rosso).Immagine pin personalizzata in annotationView in iOS

Ecco il mio codice, spero che mi può aiutare con qualche consiglio perché penso che tutto va bene ma non è ancora funzionante:

func parseJsonData(data: NSData) -> [Farmacia] { 

    let farmacias = [Farmacia]() 

    do 
    { 
     let jsonResult = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary 

     // Parse JSON data 
     let jsonProductos = jsonResult?["farmacias"] as! [AnyObject] 

     for jsonProducto in jsonProductos { 

      let farmacia = Farmacia() 
      farmacia.id = jsonProducto["id"] as! String 
      farmacia.nombre = jsonProducto["nombre"] as! String 
      farmacia.location = jsonProducto["location"] as! String 

      let geoCoder = CLGeocoder() 
      geoCoder.geocodeAddressString(farmacia.location, completionHandler: { placemarks, error in 

       if error != nil { 
        print(error) 
        return 
       } 

       if placemarks != nil && placemarks!.count > 0 { 

        let placemark = placemarks?[0] 

        // Add Annotation 
        let annotation = MKPointAnnotation() 
        annotation.title = farmacia.nombre 
        annotation.subtitle = farmacia.id 
        annotation.coordinate = placemark!.location!.coordinate 

        self.mapView.addAnnotation(annotation) 
       } 

      }) 
     } 
    } 
    catch let parseError { 
     print(parseError) 
    } 

    return farmacias 
} 

func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? { 

    let identifier = "MyPin" 

    if annotation.isKindOfClass(MKUserLocation) { 
     return nil 
    } 

    // Reuse the annotation if possible 
    var annotationView = mapView.dequeueReusableAnnotationViewWithIdentifier(identifier) 

    if annotationView == nil 
    { 
     annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier) 
     annotationView!.canShowCallout = true 
    } 

    annotationView!.image = UIImage(named: "custom_pin.png") 

    let detailButton: UIButton = UIButton(type: UIButtonType.DetailDisclosure) 
    annotationView!.rightCalloutAccessoryView = detailButton 

    print(annotationView!.image) 

    return annotationView 
} 

Grazie in anticipo,

saluti.

risposta

15

ecco la risposta:

func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? { 

    let identifier = "MyPin" 

    if annotation.isKindOfClass(MKUserLocation) { 
     return nil 
    } 

    let detailButton: UIButton = UIButton(type: UIButtonType.DetailDisclosure) 

    if let annotationView = mapView.dequeueReusableAnnotationViewWithIdentifier(identifier) { 
     annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: "pin") 
     annotationView.canShowCallout = true 
     annotationView.image = UIImage(named: "custom_pin.png") 
     annotationView.rightCalloutAccessoryView = detailButton 
    } 
    else { 
     annotationView.annotation = annotation 
    } 

    return annotationView 
} 

saluti

+1

Grazie per aver condiviso le tue soluzioni. Mi ha aiutato anche io –

+0

non funziona per lo swift 2.2 – DeyaEldeen

+0

Giù votato. 1) L'istanza "annotationView" viene creata in ambito if-let e non esiste in else-scope. 2) Se riesci a deselezionare una vista annotazione, dovresti usarla e non creare una nuova istanza. La nuova istanza deve essere creata nel dominio secondario, in cui non è possibile rimuovere dalla coda un riutilizzabile. – esbenr

41

La risposta accettata non funziona, come ha annotationView inizializzato in else blocco.

Ecco una soluzione migliore. E 'Ritiri dalla coda vista annotazione, se possibile, o ne crea uno nuovo, se non:

Swift 3, 4:

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { 
    // Don't want to show a custom image if the annotation is the user's location. 
    guard !(annotation is MKUserLocation) else { 
     return nil 
    } 

    // Better to make this class property 
    let annotationIdentifier = "AnnotationIdentifier" 

    var annotationView: MKAnnotationView? 
    if let dequeuedAnnotationView = mapView.dequeueReusableAnnotationView(withIdentifier: annotationIdentifier) { 
     annotationView = dequeuedAnnotationView 
     annotationView?.annotation = annotation 
    } 
    else { 
     annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: annotationIdentifier) 
     annotationView?.rightCalloutAccessoryView = UIButton(type: .detailDisclosure) 
    } 

    if let annotationView = annotationView { 
     // Configure your annotation view here 
     annotationView.canShowCallout = true 
     annotationView.image = UIImage(named: "yourImage") 
    } 

    return annotationView 
} 

Swift 2.2:

func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? { 
    // Don't want to show a custom image if the annotation is the user's location. 
    guard !annotation.isKindOfClass(MKUserLocation) else { 
     return nil 
    } 

    let annotationIdentifier = "AnnotationIdentifier" 

    var annotationView: MKAnnotationView? 
    if let dequeuedAnnotationView = mapView.dequeueReusableAnnotationViewWithIdentifier(annotationIdentifier) { 
     annotationView = dequeuedAnnotationView 
     annotationView?.annotation = annotation 
    } 
    else { 
     let av = MKAnnotationView(annotation: annotation, reuseIdentifier: annotationIdentifier) 
     av.rightCalloutAccessoryView = UIButton(type: .DetailDisclosure) 
     annotationView = av 
    } 

    if let annotationView = annotationView { 
     // Configure your annotation view here 
     annotationView.canShowCallout = true 
     annotationView.image = UIImage(named: "yourImage") 
    } 

    return annotationView 
} 
+1

Questo mi ha aiutato molto di più della risposta accettata, grazie mille @ Andrej Gordeev – Alk

+1

Wow !!! Questo mi ha seriamente salvato !!! Stavo avendo dei gravi problemi di perfusione, ma vedere questo esempio su come usare correttamente l'identificatore mi è stato di grande aiuto. Pensavo di usarlo correttamente anche per cominciare. Questa dovrebbe essere la risposta accettata! – BryHaw

+0

Ottimo! Grazie. – Raja

0

SWIFT 3,4

func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? { 

    if annotation.isKind(of: MKUserLocation.self) { 
     return nil 
    } 

    let annotationIdentifier = "AnnotationIdentifier" 

    var pinView = mapView.dequeueReusableAnnotationView(withIdentifier: annotationIdentifier) 
    if (pinView == nil) { 
     pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: annotationIdentifier) 
    } 

    pinView?.canShowCallout = false 

    return pinView 
} 
Problemi correlati