2015-05-04 57 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