【问题标题】:How to get continous call back when MKAnnotationView is dragged拖动MKAnnotationView时如何获得连续回调
【发布时间】:2012-08-13 07:22:23
【问题描述】:

我有MKAnnotationView 可以拖动,并且我已经实现了didChangeDragState: 委托方法,我在拖动开始和结束时获得回调,但不是连续的。我想跟踪注释的当前坐标,因为它被拖动,请帮助我一些解决方案。谢谢。

【问题讨论】:

  • 试试这个方法:- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated

标签: objective-c ios mkannotationview mapkit


【解决方案1】:

坐标可以从 annotationview.coordinates 中得到:

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

【讨论】:

  • 该方法只在注解视图的拖动状态从一种状态变为另一种状态时调用,在视图被拖动时不会连续调用。当更改为Dragging 状态时,它只会被调用一次。另外,注解上的坐标只有在状态变为Ended时才会更新,拖动时不会更新。
【解决方案2】:

据我所知,Apple 没有为您提供的方法来执行此操作,但您可以通过 KVO 实现它(h/t to 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)
}

【讨论】:

    猜你喜欢
    • 2013-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-21
    • 2022-08-19
    • 2014-01-21
    • 2017-11-30
    相关资源
    最近更新 更多