How to save the selected MKAnnotation?

久未见 提交于 2019-12-23 19:35:53

问题


I have an app that has a mapview, and it shows 20 pins (from an Array) on the map. When the user clicks on it, it can show a bubble with a right accessory button. Here come my problem: How do I know which pin was pressed? I heard something about the mapView:didSelectAnnotationView method, but I don't really understand how do you get the pin/callout index, so that I can get the information of the object at the same index of my Array? Thanks for any help!


回答1:


When that method gets called -- because your viewController class has adopted MKMapViewDelegate, you can call -indexOfObject on the array and get the index of that pin (annotation). This is with the assumption that your array holds objects of the kind of annotation class.

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

If you need more explanation, we need to know how you are adding those pins, i.e. implementation of - (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation.




回答2:


Here is a similar solution to Canopus'.

- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view
{
    if ([view.annotation isKindOfClass:[MyAnnotation class]]) 
    {
        NSInteger index = [mapView.annotations indexOfObject:view.annotation];
        NSLog(@"%d",index);
    }

Note: I was manually adding annotations to the map and then viewing their respective indexes. They don't get indexed in the order they are added to the mapView. i.e., just because you added a annotation as the fourth annotation it may have an index of 1 or 3 or whatever. Someone may have a explanation for that but it has eluded me till now. Hope this helps.



来源:https://stackoverflow.com/questions/9848292/how-to-save-the-selected-mkannotation

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