2015-05-04 60 views
2

我遇到了一個小問題。我正在嘗試爲我的mapView註釋使用自定義圖標。麻煩的是,當用戶拖動圖標時,它總是變回默認圖標。swift MapKit註解拖動狀態圖標

我在我的mapView委託中設置圖標圖像像這樣,這可以設置圖標。

// MARK: - Map Annotations 
func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! { 

    if annotation is MKUserLocation{ 
     return nil 
    } 

    let reuseId = "pin" 
    var pinView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId) as? MKPinAnnotationView 

    if(pinView == nil){ 
     if let customAnnot = annotation as? myAnnotation { 
      pinView = MKPinAnnotationView(annotation: customAnnot, reuseIdentifier: reuseId) 


      pinView!.image = UIImage(named:"pin-50.png") 


      pinView!.animatesDrop = false 
      pinView!.draggable = true 
     } 

    } else { 
     pinView!.annotation = annotation as? myAnnotation 
    } 

    return pinView! 
} 

我嘗試了一些事情來解決,但沒有一個似乎幫助。即使當我嘗試在「didChangeDragState」委託中再次設置圖標時,它仍會更改爲默認圖標。

func mapView(mapView: MKMapView!, annotationView view: MKAnnotationView!, didChangeDragState newState: MKAnnotationViewDragState, fromOldState oldState: MKAnnotationViewDragState) { 
    if newState == MKAnnotationViewDragState.Dragging { 
     println("draggin it") 
     view.image = UIImage(named:"pin-50.png") 
    } 

    if newState == MKAnnotationViewDragState.Ending { 
     //update pin location 
     if let customAnnot = view.annotation as? myAnnotation { 
      cData.updatePinLocation(customAnnot.pinID, newValue: customAnnot.coordinate) 
     } 
     view.image = UIImage(named:"pin-50.png") 

    } 

    if newState == MKAnnotationViewDragState.Starting { 
     println("start drag") 
     view.image = UIImage(named:"pin-50.png") 
    } 

} 
+1

您正在使用'MKPinAnnotationView',它繪製默認針。您應該使用或繼承'MKAnnotationView'來處理您自己的視圖。 – zisoft

回答

2

感謝zisoft,我找到了答案。這裏是工作的代碼

if (annotation is MKUserLocation) { 
     return nil 
    } 

    let reuseId = "pin" 

    var pinView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId) 

    if pinView == nil { 
     pinView = MKAnnotationView(annotation: annotation, reuseIdentifier: reuseId) 
     pinView.image = UIImage(named:"pin-50.png") 
     pinView.canShowCallout = false 
     pinView.draggable = true 
    } 
    else { 

     pinView.annotation = annotation 
    } 

    return pinView