2012-04-03 59 views
2

我已經創建了一個mapview,它具有一個按鈕,可以根據項目需求在「編輯」模式和「拖動」模式之間切換。我意識到,通過在viewForAnnotation中設置可拖動的標籤,您的註釋可以從創建拖放,但是所需的行爲不允許這樣做。我嘗試了幾種不同的方式將註釋更改爲可拖動但沒有成功。首先想到的是循環現有的註釋,並設置每一個'可拖動'和'選擇',但我得到一個無法識別的選擇器發送到實例錯誤(我嘗試實例化一個新的註釋傳入對象和重繪而在循環,但我得到了同樣的錯誤,以及):啓用和禁用註釋拖動(即時)(iOS Mapkit)

NSLog(@"Array Size: %@", [NSString stringWithFormat:@"%i", [mapView.annotations count]]); 

    for(int index = 0; index < [mapView.annotations count]; index++) { 

     if([[mapView.annotations objectAtIndex:index]isKindOfClass:[locAnno class]]){ 
      NSLog(@"** Location Annotation at Index: %@", [NSString stringWithFormat:@"%i", index]); 
      NSLog(@"* Location Marker: %@", [mapView.annotations objectAtIndex:index]); 
     } 

     if([[mapView.annotations objectAtIndex:index]isKindOfClass:[hydAnno class]]) { 
      NSLog(@"** Hydrant Annotation at Index: %@", [NSString stringWithFormat:@"%i", index]); 
      NSLog(@"* Hydrant Marker: %@", [mapView.annotations objectAtIndex:index]); 

      [[mapView.annotations objectAtIndex:index]setSelected:YES]; 
      [[mapView.annotations objectAtIndex:index]setDraggable:YES]; 
     } 
    } 

的第二個想法是用「didSelectAnnotationView」,並設置選擇和拖動時,它的選擇註解,並重置屬性時模式再次切換回來。這工作,但非常糟糕的事件並不總是火災和你的左邊挖掘註釋一次或多次前,將改變的屬性:

- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view { 
NSLog(@"Annotation Selected!"); 
if(!editMode) { 
    view.selected = YES; 
    view.draggable = YES; 
} 

}

第一次嘗試似乎是最簡單的解決方案,如果我能得到它的工作。另一方面,使用didSelect方法非常麻煩並且非常棘手。我對iOS開發很陌生,所以我很抱歉如果我忽略了一些新手,同時剔除這個問題。我很感謝社區可以提供的任何見解。非常感謝。

回答

3

第一種方法比使用didSelectAnnotationView委託方法要好。

有使「無法識別的選擇」的錯誤代碼中的問題是,它是在請註釋對象setSelected:setDraggable:(類型id<MKAnnotation>)代替其對應MKAnnotationView物體。 id<MKAnnotation>對象沒有這樣的方法,所以你得到「無法識別的選擇器」錯誤。

地圖視圖的annotations數組包含對id<MKAnnotation>(數據模型)對象的引用 - 而不是這些註釋的MKAnnotationView對象。

所以,你需要改變這一點:

[[mapView.annotations objectAtIndex:index]setSelected:YES]; 
[[mapView.annotations objectAtIndex:index]setDraggable:YES]; 

到這樣的事情:

//Declare a short-named local var to refer to the current annotation... 
id<MKAnnotation> ann = [mapView.annotations objectAtIndex:index]; 

//MKAnnotationView has a "selected" property but the docs say not to set 
//it directly. Instead, call deselectAnnotation on the annotation... 
[mapView deselectAnnotation:ann animated:NO]; 

//To update the draggable property on the annotation view, get the 
//annotation's current view using the viewForAnnotation method... 
MKAnnotationView *av = [mapView viewForAnnotation:ann]; 
av.draggable = editMode; 


還必須在viewForAnnotation委託方法更新代碼,以便它也套draggable改爲editMode而不是硬編碼的YESNO,這樣如果地圖視圖n在之後重新創建註釋的視圖,您已經在for循環中更新它,註釋視圖將具有draggable的正確值。

+0

謝謝你幫我解決這個問題!我有一種感覺,我試圖操縱錯誤的對象。我需要解決的唯一問題是,當我切換到拖動模式時,我需要在拖動它之前敲擊一次註釋(而不是立即拖動)。我通過在viewAnnotation中調用setSelected和setDraggable來解決此問題,而不是annotation.selected和annotation.draggable。 – ninehundredt 2012-04-03 15:30:11