Reputation: 341
I have a custom MKAnnotationView
that I am loading from an XIB
. When I first load the mapview, I have several standard MKAnnotationView
.
When a user selects one, the custom MKAnnotationView
is presented. I would like for the user to be able to tap anywhere inside the custom annotation view to present a new view controller.
What I've tried (all of these were suggestions I found here on StackOverflow):
What is strange is that if I drag the map while the annotation is present, the button works fine. The issue only shows up when I first show the custom view.
Any ideas would be appreciated.
Upvotes: 4
Views: 878
Reputation: 4218
You should checkout out the MKMapKit Delegate documentation it has lots of good methods you can use to do exactly what you're trying to do. I would absolutely not try and add a UIButton to a annotation view.
Managing Annotation Views
– mapView:viewForAnnotation:
– mapView:didAddAnnotationViews:
– mapView:annotationView:calloutAccessoryControlTapped:
Dragging an Annotation View
– mapView:annotationView:didChangeDragState:fromOldState:
Selecting Annotation Views
– mapView:didSelectAnnotationView:
– 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];
}
//Add an Image!
annotationView.image = [UIImage imageNamed:@"trashMarker.png"];
//Move the Frame Around!
[annotationView setFrame:CGRectMake(annotationView.frame.origin.x, annotationView.frame.origin.y - annotationView.frame.size.height, annotationView.frame.size.height, annotationView.frame.size.width)];
//Finally Set it as the annotation!
annotationView.annotation = annotation;
//Return the annotationView so the MKMapKit can display it!
return annotationView;
}}
Your subclass of the MKAnnotation (IE conforms to protocol) should contain a tag by default (I think) but if it doesn't just add one yourself with a property so you can distinguish between the 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)
{
//SHOW VIEW CONTROLLER
}}
For more examples you can refer to our open source project for Green Up Vermont
Upvotes: 0