检测触摸了哪个特定的地图引脚

时间:2014-10-31 22:50:16

标签: ios mkmapview mkannotation

我有一个包含大量引脚的地图视图,每个引脚都有一个唯一的注释。地图还显示用户位置的脉冲蓝点。到目前为止,我只能确定是否触摸了引脚,而不是触摸的SPECIFIC引脚。

如何确定地图中用户触摸的特定图钉?我正在使用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");

}

2 个答案:

答案 0 :(得分: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);
    }
}

答案 1 :(得分: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
{
}

只需使用此代码。希望这对您有用。 :)