2016-08-02 49 views
3

我已將其他堆棧帖子和教程轉換爲自定義註釋圖像,但似乎不起作用。沒有錯誤或運行時錯誤出現,只是註釋圖像不會更改。Swift - 更改註釋圖像無法正常工作

只是我在行annotationView!.image = UIImage(named: "RaceCarMan2png.png")上設置了一個斷點,它表明該行被調用,但沒有任何反應。我將衷心感謝您的幫助。謝謝。

func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? { 
    if annotation is MKUserLocation { 
     return nil 
    } 

    let identifier = "MyCustomAnnotation" 

    var annotationView = mapView.dequeueReusableAnnotationViewWithIdentifier(identifier) 
    if annotationView == nil { 
     annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier) 
     annotationView?.canShowCallout = true 

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

    } else { 
     annotationView!.annotation = annotation 
    } 


    configureDetailView(annotationView!) 

    return annotationView 
} 

func configureDetailView(annotationView: MKAnnotationView) { 
     annotationView.detailCalloutAccessoryView = UIImageView(image: UIImage(named: "url.jpg")) 
} 

回答

4

的問題是,你」重新使用MKPinAnnotationView。如果你使用MKAnnotationView,你會看到你的形象:

class ViewController: UIViewController, MKMapViewDelegate { 

    @IBOutlet weak var mapView: MKMapView! 

    private func addAnnotation(coordinate coordinate: CLLocationCoordinate2D, title: String, subtitle: String) { 
     let annotation = MKPointAnnotation() 
     annotation.coordinate = coordinate 
     annotation.title = title 
     annotation.subtitle = subtitle 
     mapView.addAnnotation(annotation) 
    } 

    func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? { 
     if annotation is MKUserLocation { return nil } 

     let identifier = "CustomAnnotation" 

     var annotationView = mapView.dequeueReusableAnnotationViewWithIdentifier(identifier) 

     if annotationView == nil { 
      annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: identifier) 
      annotationView!.canShowCallout = true 
      annotationView!.image = UIImage(named: "star.png")! // go ahead and use forced unwrapping and you'll be notified if it can't be found; alternatively, use `guard` statement to accomplish the same thing and show a custom error message 
     } else { 
      annotationView!.annotation = annotation 
     } 

     return annotationView 
    } 

    ... 
} 

產量:

Chicago star

在過去的(如iOS版8),設定的MKPinAnnotationViewimage似乎正常工作,但在iOS 9.x,似乎無論如何使用一個引腳。對於稱爲MKPinAnnotationView的類而言,這並非完全不合理的行爲,並且使用MKAnnotationView可以避免此問題。

+0

非常感謝你的工作! –

0

調用返回

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

return annotationView 

前及斷點檢查它是否是確定的,如果裏面 向我們展示你的形象截圖項目太:)