2010-08-12 53 views
9

我在我的地圖上有一個自定義MKOverlayView,我想檢測觸摸。但是,我似乎無法讓疊加層做出迴應。我希望這將是一樣傻乎乎忘記userInteractionEnabled設置爲YES東西......但很可惜,沒有運氣MKOverlayView和觸摸

....目前,這裏就是我有它:

//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; 

} 

我的自定義覆蓋類簡單地實現的touchesBegan,並延伸MKCircleView

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    NSLog(@"touch!"); 
} 

回答

12

首先,添加一個手勢識別器到您的MKMapView(注:這是假設ARC):

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

在識別動作,你可以計算出抽頭點是否通過類似下面是一個觀點:

- (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

感謝你們的工作完全這樣一個明確的答案 – 2012-11-09 13:24:30