You should check out the MKMapKit Delegate documentation, which has many good methods that you can use to do exactly what you are trying to do. I would absolutely not try and add UIButton to the annotation view.
Manage annotation views - mapView: viewForAnnotation: - mapView: didAddAnnotationViews: - mapView: annotationView: calloutAccessoryControlTapped: Drag and drop annotations - mapView: annotationView: didChangeDragState: fromOldState: Select annotations - mapView: didSelectAnnotation:
- mapView: didDeselectAnnotationView:
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation { if([annotation isKindOfClass: [MKUserLocation class]]) { return nil; } else if([annotation isKindOfClass:[MYCLASS class]]) { static NSString *annotationViewReuseIdentifier = @"annotationViewReuseIdentifier"; MKAnnotationView *annotationView = (MKAnnotationView *)[self.mapView dequeueReusableAnnotationViewWithIdentifier:annotationViewReuseIdentifier]; if (annotationView == nil) { annotationView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:annotationViewReuseIdentifier]; }
Your subclass MKAnnotation (IE conforms to the protocol) should contain a default tag (I think), but if it doesnβt just add it yourself, so that you can distinguish between different markers on the map. Your method should look something like this
-(void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view { MYCLASS *selectedMapPin = view.annotation; if(selectedMapPin.tag == MY_PIN_TAG) {
For more examples, you can refer to our open source project for Green Up Vermont
Vermont iOS green app
source share