2014-10-31 32 views
1

我有大量引腳的地圖視圖,每個引腳都有獨特的註釋。該地圖還顯示用戶位置的脈衝藍點。到目前爲止,我只能確定一個針是否被觸摸,而不是被觸摸的特定針。檢測觸摸了哪個特定的地圖引腳

如何確定用戶觸摸的地圖中的特定引腳?我正在使用Xcode v6.1。示例代碼(對於許多引腳之一):

- (void)viewDidLoad { 

    [super viewDidLoad]; 

//** Data for Location 1 ** 
    MKCoordinateRegion region = { {0.0, 0.0 }, { 0.0, 0.0 } }; 
    region.center.latitude = 45.5262223; 
    region.center.longitude = -122.63642379999999; 
    region.span.longitudeDelta = 0.01f; 
    region.span.latitudeDelta = 0.01f; 

    [mapView setRegion:region animated:YES]; 

    [self.mapView setDelegate:self]; 

    DisplayMap *ann = [[DisplayMap alloc] init]; 
    ann.title = @"This is Location 1"; 
    ann.subtitle = @"1234 North Main Street"; 
    ann.coordinate = region.center; 
    [self.mapView addAnnotation:ann]; 

- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view { 

    NSLog(@"This logs when any pin is touched, need to know which pin"); 

} 
+0

完美的作品!非常感謝您的準確答案和詳細解釋。對不起,我不能投票你的答案,但我的聲譽不夠高。但是,再次感謝! – Cheesehead1957 2014-11-01 17:54:08

回答

3

didSelectAnnotationView中,view參數傳遞給該方法包含它與相關聯的註釋的參考。

使用引用之前,您應該檢查它是什麼類型(例如,使用isKindOfClass)並相應地進行處理。這是因爲代理方法將在任何註釋點擊時被調用,其中包括類型爲MKUserLocation的用戶位置藍點。您的自定義註釋對象也有可能具有非標準屬性,並嘗試在錯誤類型的註釋中訪問這些屬性會導致異常。

例子:

- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view { 

    //Annotation that was selected is in the view parameter... 
    id<MKAnnotation> annSelected = view.annotation; 

    //See if this annotation is our custom type (DisplayMap) 
    //and not something else like MKUserLocation... 
    if ([annSelected isKindOfClass:[DisplayMap class]]) 
    { 
     //Now we know annSelected is of type DisplayMap 
     //so it's safe to cast it as type DisplayMap... 
     DisplayMap *dm = (DisplayMap *)annSelected; 

     NSLog(@"Pin touched: title=%@", dm.title); 
    } 
} 
+0

來自墨西哥的感謝! =) – Fabio 2015-07-15 04:57:48

0
- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)aView 
{ 
    NSInteger indexPathTag=aView.tag; 
    [mapView deselectAnnotation:aView.annotation animated:YES]; 

} 
- (void)mapView:(MKMapView *)mapView didDeselectAnnotationView:(MKAnnotationView *)aView 
{ 
} 

只需使用這個code.Hope這會爲你工作。 :)

+0

謝謝!我試過,但我有一個問題時,增加標籤:( – Fabio 2015-07-16 03:01:01