I can't seem to get the long press gesture recognizer to work on the annotation view, only the map view. The abridged version of my code is:
@interface AppDelegate : UIResponder <UIApplicationDelegate, CLLocationManagerDelegate, MKMapViewDelegate, UIGestureRecognizerDelegate, UIActionSheetDelegate>
{
CLLocationManager *locationManager;
// Views
IBOutlet MKMapView *mapView;
IBOutlet MKAnnotationView *annotationView;
UILongPressGestureRecognizer *longPress;
}
and parts of the implementation in AppDelegate.m ...
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
locationManager = [[CLLocationManager alloc] init];
[locationManager setDelegate:self];
[mapView setShowsUserLocation:YES];
longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self
action:@selector(deleteSelectedAnnotation:)];
[[self window] makeKeyAndVisible];
return YES;
}
- (void)mapView:(MKMapView *)mv didAddAnnotationViews:(NSArray *)views
{
annotationView = [views objectAtIndex:0];
[annotationView addGestureRecognizer:longPress];
id <MKAnnotation> mp = [annotationView annotation];
MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance([mp coordinate], 250, 250);
[mv setRegion:region animated:YES];
}
- (IBAction)deleteSelectedAnnotation:(UIGestureRecognizer *)sender
{
if (sender.state == UIGestureRecognizerStateBegan)
{
NSLog(@"long press");
UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"Delete Record?"
delegate:self
cancelButtonTitle:nil
destructiveButtonTitle:nil
otherButtonTitles:@"Yes",@"No",nil];
[actionSheet showInView:mapView];
[actionSheet release];
}
}
So this whole thing works if i change the view object in line [annotationView addGestureRecognizer:longPress]
to mapView
. But I only want the action to occur if the user is pressing the annotation, not anywhere on the map. What am I doing wrong?
Thanks.
You can check if the touch is inside the annotation view's bounds:
UIView *annotationView = [mapView viewForAnnotation:myAnnotation];
if ( annotationView && CGRectContainsPoint(annotationView.bounds, [sender locationInView:annotationView]) )
{
// we can continue
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.