[英]Using UILongPressGestureRecognizer to Remove MKAnnotation
我似乎無法讓長按手勢識別器在注釋視圖上工作,僅在地圖視圖上工作。 我的代碼的簡化版本是:
@interface AppDelegate : UIResponder <UIApplicationDelegate, CLLocationManagerDelegate, MKMapViewDelegate, UIGestureRecognizerDelegate, UIActionSheetDelegate>
{
CLLocationManager *locationManager;
// Views
IBOutlet MKMapView *mapView;
IBOutlet MKAnnotationView *annotationView;
UILongPressGestureRecognizer *longPress;
}
以及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];
}
}
因此,如果我將[annotationView addGestureRecognizer:longPress]
行中的視圖對象更改為mapView
則整個工作正常。 但是我只希望操作在用戶按下注釋時發生,而不是在地圖上的任何地方。 我究竟做錯了什么?
謝謝。
您可以檢查觸摸是否在注釋視圖的范圍內:
UIView *annotationView = [mapView viewForAnnotation:myAnnotation];
if ( annotationView && CGRectContainsPoint(annotationView.bounds, [sender locationInView:annotationView]) )
{
// we can continue
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.