A clean solution to find out which MKAnnotation was involved?

Ok, so you usually have an X object that you want to annotate inside MKMapView. You do this:

DDAnnotation *annotation = [[DDAnnotation alloc] initWithCoordinate: poi.geoLocation.coordinate title: @"My Annotation"]; [_mapView addAnnotation: annotation]; 

Then you create the annotation inside

 - (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation; 

And when some callouts come in, you handle the event internally:

 - (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control; 

What is the cleanest solution for moving X to the latest tap event?

+6
cocoa-touch mkmapview mkannotation
source share
2 answers

If I understand your question, you should add a link or property to your DDAnnotation class so that you can access the object in your calloutAccessoryControlTapped method.

 @interface DDAnnotation : NSObject <MKAnnotation> { CLLocationCoordinate2D coordinate; id objectX; } @property (nonatomic, readonly) CLLocationCoordinate2D coordinate; @property (nonatomic, retain) id objectX; 

When you create the annotation:

 DDAnnotation *annotation = [[DDAnnotation alloc] initWithCoordinate:poi.geoLocation.coordinate title: @"My Annotation"]; annotation.objectX = objectX; [_mapView addAnnotation: annotation]; 

Then:

 - (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control{ DDAnnotation *anno = view.annotation; //access object via [anno.objectX callSomeMethod]; } 
+17
source share

I did it and it worked out well!

This is exactly what I need, because I had to do something when the card was pressed, but allowed to enter the annotation stream normally.

 - (void)viewDidLoad { [super viewDidLoad]; UIGestureRecognizer *g = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleGesture:)] autorelease]; g.cancelsTouchesInView = NO; [self.mapView addGestureRecognizer:g]; } - (void) handleGesture:(UIGestureRecognizer*)g{ if( g.state == UIGestureRecognizerStateEnded ){ NSSet *visibleAnnotations = [self.mapView annotationsInMapRect:self.mapView.visibleMapRect]; for ( id<MKAnnotation> annotation in visibleAnnotations.allObjects ){ UIView *av = [self.mapView viewForAnnotation:annotation]; CGPoint point = [g locationInView:av]; if( [av pointInside:point withEvent:nil] ){ // do what you wanna do when Annotation View has been tapped! return; } } //do what you wanna do when map is tapped } } 
0
source share

All Articles