MKOverlayView and touches

后端 未结 1 1702
臣服心动
臣服心动 2021-02-06 04:03

i have an custom MKOverlayView on my map and i would like to detect touches. However, i can\'t seem to get the overlay to respond. i was hoping it was going to be something as d

相关标签:
1条回答
  • 2021-02-06 04:43

    Firstly, add a gesture recogniser to your MKMapView (note: this is assuming ARC):

    [myMapView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(mapTapped:)]];
    

    In the recognizer action, you can figure out whether the tap point was in a view via something like the following:

    - (void)mapTapped:(UITapGestureRecognizer *)recognizer
    {
      MKMapView *mapView = (MKMapView *)recognizer.view;
      id<MKOverlay> tappedOverlay = nil;
      for (id<MKOverlay> overlay in mapView.overlays)
      {
        MKOverlayView *view = [mapView viewForOverlay:overlay];
        if (view)
        {
          // Get view frame rect in the mapView's coordinate system
          CGRect viewFrameInMapView = [view.superview convertRect:view.frame toView:mapView];
          // Get touch point in the mapView's coordinate system
          CGPoint point = [recognizer locationInView:mapView];
          // Check if the touch is within the view bounds
          if (CGRectContainsPoint(viewFrameInMapView, point))
          {
            tappedOverlay = overlay;
            break;
          }
        }
      }
      NSLog(@"Tapped view: %@", [mapView viewForOverlay:tappedOverlay]);
    }
    
    0 讨论(0)
提交回复
热议问题