开发者

MKOverlayView and touches

开发者 https://www.devze.com 2023-01-11 03:22 出处:网络
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 dumb as forgetting to se

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 dumb as forgetting to set userInteractionEnabled to YES...but alas, no luck there

....currently, here is how i have it:

//map delegate overlay:
- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay
{

     if (_radiusView !=nil) {
          [_radiusView removeFromSuperview];
          [_radiusView release];
          _radiusView = nil;
     }
     _radiusView = [[CustomRadiusView alloc]initWithCircle:overlay];
     _radiusView.userInteractionEnabled = YES;
     _radiusView.strokeColor = [UIColor blueColor];
     _radiusView.fillColor = [UIColor grayColor];
     _radiusView.lineWidth = 1.0;
     _radiusView.alpha = 0;

     //fade in radius view
     [UIView beginAnimations:@"fadeInRadius" context:nil];
     [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
     [UIView setAnimationDuration:0.6];
     _radiusView.alpha = .3;
     [UIView commitAnimations];

     return _radiusView;

}   

my custom overlay class simply implements touchesBegan, and extends MKCircleView

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
  NSLog(@开发者_如何学编程"touch!");
}


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

精彩评论

暂无评论...
验证码 换一张
取 消