如何在拖动MKAnnotationView时进行连续回调

时间:2012-08-13 07:22:23

标签: objective-c ios mkannotationview mapkit

我有MKAnnotationView这是可拖动的,我已经实现了didChangeDragState:委托方法,我在拖动的开始和结束时得到回调,但不是连续的。我想在拖动时跟踪注释的当前坐标,请帮我解决一些问题。谢谢。

2 个答案:

答案 0 :(得分:0)

坐标可以从annotationview.coordinates获得:

  -(void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view   
  didChangeDragState:(MKAnnotationViewDragState)newState fromOldState:
  (MKAnnotationViewDragState)oldState
  {
  CLLocationCoordinate2D currentCoordinates = view.annotation.coordinate;
  }

答案 1 :(得分:0)

据我所知,苹果提供的方式并非如此,但您可以通过KVO(h / t到this answer)来实现。

您还需要手动确定注释视图的坐标,因为注释的坐标在输入MKAnnotationViewDragStateEnding之后才会更新。

完整的解决方案如下所示:

// Somewhere in your code before the annotation view gets dragged, subscribe your observer object to changes in the annotation view's frame center
annotationView.addObserver(DELEGATE_OBJECT, forKeyPath: "center", options: NSKeyValueObservingOptions.New, context: nil)

// Then in the observer's code, fill out the KVO callback method
// Your observer will need to conform to the NSKeyValueObserving protocol -- all `NSObject`s already do
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
    // Check that we're observing an annotation view. The `where` clause can be omitted if you're only observing changes in its frame, or don't care about extra calls
    if let annotationView = object as? MKAnnotationView where keyPath == "center" {
        // Defined below, `coordinateForAnnotationView` converts a CGPoint measured within a given MKMapView to the geographical coordinate represented in that location
        let newCoordinate = coordinateForAnnotationView(pin, inMapView: self.mapView)

        // Do stuff with `newCoordinate`
    }
}

func coordinateForAnnotationView(annotationView: MKAnnotationView, inMapView mapView: MKMapView) -> CLLocationCoordinate2D {
    // Most `MKAnnotationView`s will have a center offset, including `MKPinAnnotationView`
    let trueCenter = CGPoint(x: annotationView.center.x - annotationView.centerOffset.x,
        y: annotationView.center.y - annotationView.centerOffset.y)

    return mapView.convertPoint(trueCenter, toCoordinateFromView: mapView)
}