Custom MKAnnotationView periodically recognizes touch

I have a custom MKAnnotationView that I load from XIB . When I first load mapview, I have some standard MKAnnotationView .

When the user selects one, the custom MKAnnotationView . I would like the user to be able to use any element of the user annotation to represent the new view controller.

What I tried (all these were suggestions that I found here in StackOverflow):

It is strange that if I drag the map while the annotation is present, the button works fine. The problem only occurs when the user view is first shown.

Any ideas would be appreciated.

+4
source share
1 answer

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]; } //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 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) { //SHOW VIEW CONTROLLER }} 

For more examples, you can refer to our open source project for Green Up Vermont

Vermont iOS green app

0
source

Source: https://habr.com/ru/post/1497730/


All Articles