How Do I Determine Which MKAnnotation is clicked?

亡梦爱人 提交于 2019-12-12 05:50:00

问题


I'm a noob to iphone developoment and i am trying to determine the int value of an annotation so I can then take that int value and cross reference it to an array to get a corresponding value. However, when i try to get the int value with the .tag method the value always returns as zero. If I have 5 annontations I need to be able to determine which annontation is 0,1,2,3 and 4. Any help is greatly appreciated.

MY CODE

- (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;    
}

回答1:


The tag property is something you have to set. I think you're not setting it anywhere.

Certainly for the UIButton that you create using buttonWithType. The default tag value is 0, so you're always going to get 0 asking for the tag right after the view (Button) is created.




回答2:


Write below code to get index value

- (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];
  }
}

With my previous post https://stackoverflow.com/a/34742122/3840428



来源:https://stackoverflow.com/questions/15145448/how-do-i-determine-which-mkannotation-is-clicked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!