如何确定单击哪个MKAnnotation?

时间:2013-02-28 20:54:54

标签: iphone dictionary indexing int mkannotation

我是iphone开发的菜鸟,我正在尝试确定注释的int值,因此我可以获取该int值并将其交叉引用到数组以获取相应的值。但是,当我尝试使用.tag方法获取int值时,该值始终返回为零。如果我有5个通知,我需要能够确定哪个通道是0,1,2,3和4.任何帮助都非常感谢。

我的代码

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

if (view.selected==YES) {
    NSInteger annotationIndex = view.tag; //Always returns zero
    NSLog(@"annotationIndex: %i", annotationIndex);
  }
} 

-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation {
// Define your reuse identifier.
  static NSString *identifier = @"MapPoint";   

  if ([annotation isKindOfClass:[MapPoint class]]) {
    MKPinAnnotationView *annotationView = (MKPinAnnotationView *) [self.mapView dequeueReusableAnnotationViewWithIdentifier:identifier];
    if (annotationView == nil) {
        annotationView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:identifier];
    } else {
        annotationView.annotation = annotation;
    }
    annotationView.enabled = YES;
    annotationView.canShowCallout = YES;
    annotationView.animatesDrop = YES;

    UIButton* rightButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
    NSInteger clickIndex = rightButton.tag; //Always returns zero, despite there being 5 annotations
    NSLog(@"buttonIndex: %i", clickIndex); 
    [rightButton addTarget:self
                    action:@selector(showDetails:)
          forControlEvents:UIControlEventTouchUpInside];
    annotationView.rightCalloutAccessoryView = rightButton;

    return annotationView;
  }
  return nil;    
}

2 个答案:

答案 0 :(得分:1)

标签属性是您必须设置的内容。我认为你没有把它放在任何地方。

当然对于使用buttonWithType创建的UIButton。默认标记值为0,因此在创建视图(按钮)后,您总是要求0来询问标记。

答案 1 :(得分:0)

编写以下代码以获取索引值

- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view {
  // Annotation is your custom class that holds information about the annotation
  if ([view.annotation isKindOfClass:[Annotation class]]) {
    Annotation *annot = view.annotation;
    NSInteger index = [self.arrayOfAnnotations indexOfObject:annot];
  }
}

上一篇文章https://stackoverflow.com/a/34742122/3840428