iPhone:在MKMapView中检测Tap

如何检测MKMapView实例上的单击? 我是否必须touchesEnded MKMapView ,然后覆盖touchesEnded方法?

谢谢,

-克里斯

希望这会有所帮助: 如何拦截触摸MKMapView或UIWebView对象上的事件?

如果您只是希望在不影响地图的任何其他触摸行为的情况下获得点击手势的通知,则您将需要使用UITapGestureRecognizer 。 它非常简单,只需输入一些像这样的代码。

 UITapGestureRecognizer* tapRec = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didTapMap:)]; [theMKMapView addGestureRecognizer:tapRec]; [tapRec release]; 

每当theMKMapView接收到一个轻theMKMapView手势时,这将调用didTapMap并且所有的捏合和拖动手势仍将像以前一样工作。

或者根据你要做的事情,添加一个MKAnnotation (推针,带标注),这样你就可以点击 – 然后你的地图代表将收到一个事件,例如。

mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control

在iOS 8上完美运行

 - (void)viewDidLoad { [super viewDidLoad]; UITapGestureRecognizer *doubleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:nil]; doubleTap.numberOfTapsRequired = 2; doubleTap.numberOfTouchesRequired = 1; [self.mapView addGestureRecognizer:doubleTap]; UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleGesture:)]; singleTap.numberOfTapsRequired = 1; singleTap.numberOfTouchesRequired = 1; [singleTap requireGestureRecognizerToFail: doubleTap]; [self.mapView addGestureRecognizer:singleTap]; } - (void)handleGesture:(UIGestureRecognizer *)gestureRecognizer { if (gestureRecognizer.state != UIGestureRecognizerStateEnded) return; //Do your work ... } 

你现在无法拦截地图视图上的触摸,你可以尝试在那里分层不透明的视图,看它是否接受了触摸……

只需添加一些代码片段作为@ tt-kilew答案的插图。 在我的情况下,我想在地图上指出用户自己,但不想打断他的拖动触摸。

 @interface PrettyViewController ()  @property (weak, nonatomic) IBOutlet MKMapView *mapView; @property (assign, nonatomic) BOOL userTouchTheMap; @end @implementation PrettyViewController #pragma mark - UIResponder - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { [super touchesBegan:touches withEvent:event]; self.userTouchTheMap = [[touches anyObject].view isEqual:self.mapView]; } #pragma mark - MKMapViewDelegate - (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation { //We just positioning to user if (!self.userTouchTheMap) { CLLocationDistance radius = 5000; [self.mapView setRegion:MKCoordinateRegionMakeWithDistance(userLocation.location.coordinate, 2*radius, 2*radius) animated:YES]; } } @end 

我找不到任何工作,但我提出了这个不完美的解决方案:在viewDidLoad中

 let singleTapRecognizer = UITapGestureRecognizer(target: self, action: #selector(onMapClicked)) singleTapRecognizer.delegate = self mapView.addGestureRecognizer(singleTapRecognizer) 

在代表中:

 func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool { return touch.view!.frame.equalTo(mapView.frame) }