Tom
Tom

Reputation: 4059

Check if an MKAnnotation is selected on a map?

I have a really simple question: how can I check if an MKAnnotation is selected on a map?

I can't see a selected like (GET) property.

I hope the solution would not be by triggering selected/deselected events and store its result in a property and check them if I need. There must be a more straightforward one.

Thanks very much!

Upvotes: 4

Views: 3304

Answers (3)

incanus
incanus

Reputation: 5128

Check out -[MKMapView selectedAnnotations].

Upvotes: 6

Nishant Tyagi
Nishant Tyagi

Reputation: 9913

Just an update to this -- in iOS 4 there are MKMapViewDelegate methods that can be used to track annotation selection and de-selection:

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

You can use an Observer for Selected annotation Event:

[pin addObserver:self
      forKeyPath:@"selected" 
         options:NSKeyValueObservingOptionNew
         context:@"ANSELECTED"];
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{

    NSString *action = (NSString*)context;

    if([action isEqualToString:@"ANSELECTED"]){

        BOOL annotationAppeared = [[change valueForKey:@"new"] boolValue];
        if (annotationAppeared) {
            // clicked on an Annotation
        }
        else {
            // Annotation disselected
        }
    }
}

Upvotes: 1

Gaurav Rastogi
Gaurav Rastogi

Reputation: 2145

Making use of the delegate method of MKMapView didSelectAnnotationView: use can get the event MKAnnotation Selected

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

Hope it will help you.

Upvotes: 6

Related Questions