2012-08-13 22 views
2

我有MKAnnotationView這是拖拽能力,並且我實現了didChangeDragState:委託方法,在拖拽的開始和結束處獲得回調,但不是連續的。我想跟蹤當前拖動的註釋座標,請幫助我解決一些問題。謝謝。當拖動MKAnnotationView時如何獲得連續回撥

+0

嘗試使用這種方法: ' - (空)的MapView:(*的MKMapView)的MapView regionDidChangeAnimated:(BOOL)animated' – Dhruv 2012-08-13 11:31:48

回答

0

的座標可以從annotationview.coordinates可以得到:

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

此方法僅調用的時候,註釋視圖的拖動狀態從一種狀態變爲另一種狀態,視圖被拖動時不會被連續調用。當它改變到「Dragging」狀態時它只會被調用一次。此外,註釋上的座標僅在狀態更改爲「已結束」時更新,並且在拖動時未更新。 – Ziewvater 2016-01-07 01:02:22

0

據我所知,沒有爲你做這個蘋果提供的方式,但你可以通過志願實現它( 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) 
}