当MKAnnotationView被拖动时如何获得连续的回调

3

我有一个可以拖动的 MKAnnotationView,并且我已经实现了 didChangeDragState: 代理方法,在拖动开始和结束时会得到回调,但不是连续的。我想要在注释被拖动时跟踪其当前坐标,请帮我提供一些解决方案。谢谢。


尝试使用这个方法: - (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated - Dhruv
2个回答

0
据我所知,苹果没有提供一种方法让你这样做,但是你可以通过 KVO 实现(感谢 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)
}

0

坐标可以从annotationview.coordinates获得:

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

当注释视图的拖动状态从一个状态更改为另一个状态时,才会调用此方法,它不会在视图被拖动时连续调用。仅在更改为“Dragging”状态时调用一次。此外,注释上的坐标仅在状态更改为“Ended”时更新,而在拖动时不会更新。 - Ziewvater

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接