如何使用Swift(IOS)实现可拖动的MKPointAnnotation?

时间:2014-10-07 04:36:03

标签: ios swift

我是ios中的noob,我需要使用swift在MKPointAnnotation中实现可拖动的MKMapView。我需要一个例子。我现在实现MKMapView并在地图中添加MKPointAnnotation(addAnnotation)。

我的英语不好,请帮帮我!

我发现了 link ,但我不明白。

2 个答案:

答案 0 :(得分:9)

您必须创建一个派生自MKMapView的自定义类。该类必须实现MKMapViewDelegate协议。

然后您需要两个步骤:创建注释对象并为该注释创建视图。

创建注释:

代码中的某处,取决于您的需求:

let annotation = MKPointAnnotation()
annotation.setCoordinate(location)  // your location here
annotation.title = "My Title"
annotation.subtitle = "My Subtitle"

self.mapView.addAnnotation(annotation)

创建注释视图

func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
    if annotation is MKPointAnnotation {
        let pinAnnotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "myPin")

        pinAnnotationView.pinColor = .Purple
        pinAnnotationView.draggable = true
        pinAnnotationView.canShowCallout = true
        pinAnnotationView.animatesDrop = true

        return pinAnnotationView
    }

    return nil
}

答案 1 :(得分:4)

这是我的示例代码。此代码允许您长按地图以添加点并拖动该点,直到您从屏幕上释放手指。另请查看您必须在地图视图上添加的gestureRecognizer。希望这可以帮助你。

class TravelLocationMapController: UIViewController, MKMapViewDelegate {


@IBOutlet var mapView: MKMapView!

var dragPin: MKPointAnnotation!

override func viewDidLoad() {
    super.viewDidLoad()

    mapView.delegate = self
    let gestureRecognizer = UILongPressGestureRecognizer(target: self, action: "addPin:")
    gestureRecognizer.numberOfTouchesRequired = 1

    mapView.addGestureRecognizer(gestureRecognizer)
}

func addPin(gestureRecognizer:UIGestureRecognizer){
    let touchPoint = gestureRecognizer.locationInView(mapView)
    let newCoordinates = mapView.convertPoint(touchPoint, toCoordinateFromView: mapView)
    if dragPin != nil {
        dragPin.coordinate = newCoordinates
    }

    if gestureRecognizer.state == UIGestureRecognizerState.Began {
        dragPin = MKPointAnnotation()
        dragPin.coordinate = newCoordinates
        mapView.addAnnotation(dragPin)
    } else if gestureRecognizer.state == UIGestureRecognizerState.Ended {            
        dragPin = nil
    }
}

func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
    if annotation is MKPointAnnotation {
        let pinAnnotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "myPin")

        pinAnnotationView.pinTintColor = UIColor.purpleColor()
        pinAnnotationView.animatesDrop = true

        return pinAnnotationView
    }
    return nil
}

func mapView(mapView: MKMapView, didSelectAnnotationView view: MKAnnotationView) {
    let lat = view.annotation?.coordinate.latitude
    let long = view.annotation?.coordinate.longitude

    print("Clic pin lat \(lat) long \(long)")

}