I have populated a couple of locations on MKMapView using MKPointAnnotation(s). On tapping annotations I am showing some options with UIActionSheet menu. The options have some delete functionality which would delete the selected annotation on map when user taps the delete option on UIActionSheet. The issue is that I am not able to determine which annotation point is clicked, I seem to have no reference to it.
The code that adds annotation point is:
while(looping array of locations)
{
MKPointAnnotation *annotationPoint = [[MKPointAnnotation alloc] init];
annotationPoint.coordinate = {coord of my location}
annotationPoint.title = [anObject objectForKey:@"castTitle"];
annotationPoint.subtitle = [anObject objectForKey:@"storeName"];
[self.mainMapView addAnnotation:annotationPoint];
}
The code to show UIActionSheet on tapping annotation is:
-(MKAnnotationView*)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation{
if([annotation isKindOfClass:[MKUserLocation class]])
return nil;
static NSString* AnnotationIdentifier = @"AnnotationIdentifier";
MKPinAnnotationView *pinView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationIdentifier];
pinView.animatesDrop = YES;
pinView.canShowCallout = YES;
pinView.pinColor = [self getAnnotationColor];
UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
[rightButton setTitle:annotation.title forState:UIControlStateNormal];
[rightButton addTarget:self action:@selector(showOptions:) forControlEvents:UIControlEventTouchUpInside];
pinView.rightCalloutAccessoryView = rightButton;
return pinView;
}
-(IBAction)showOptions:(id)sender
{
UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:NSLocalizedString(@"", @"") delegate:self cancelButtonTitle:NSLocalizedString(@"Cancel", @"Cancel") destructiveButtonTitle:nil otherButtonTitles:NSLocalizedString(@"Delete", @"Delete"), nil];
[sheet showInView:[self.view window]];
}
Seems like there are two approaches.
If only one annotation can be selected at a time, you could access the
-selectedAnnotationsproperty of the enclosingMKMapView.Another approach is to inspect
senderinshowOptions:, which is a reference to theUIButtonthat triggered the action. Find out its enclosingMKAnnotationView, which will give you the associated-annotation. You could then either stash this as an ivar or (my preferred approach) use some runtime magic – in the form ofobjc_setAssociatedObject(), declared in<objc/runtime.h>– to attach a reference to the annotation to the action sheet, allowing easy retrieval in its delegate callback.(You could actually do this back in the button creation phase if you wanted, and attach a reference to the annotation to the UIButton, which can be picked up directly in
showOptions:and reattached to the action sheet.But
[MKMapView selectedAnnotations]I would think is the easier way to go if it suits your needs.