2011-06-22 53 views
9

在我目前正在設計的應用程序中,我有一個MKMapView覆蓋層(自定義MKPolylines btw),我希望能夠檢測這些覆蓋層上的觸摸事件併爲每個觸摸事件分配一個特定的操作覆蓋。任何人都可以幫我解決這個問題嗎? 謝謝!在MKMapView的覆蓋物上觸摸事件

貝尼亞

回答

0

萬一它可能會幫助一些你...... 我無法找到一個方法來做到這一點,但我加的註釋上我的疊加(反正我需要做的是顯示一些信息),然後我可以在此註釋中獲得觸摸事件。我知道這不是最好的辦法,但在我的情況下,也許是你的,它的工作原理;)!

18

這可以通過組合How to intercept touches events on a MKMapView or UIWebView objects?How to determine if an annotation is inside of MKPolygonView (iOS)來解決。加入看這個會引導:

WildcardGestureRecognizer * tapInterceptor = [[WildcardGestureRecognizer alloc] init]; 
tapInterceptor.touchesBeganCallback = ^(NSSet * touches, UIEvent * event) { 
    UITouch *touch = [touches anyObject]; 
    CGPoint point = [touch locationInView:self.mapView]; 

    CLLocationCoordinate2D coord = [self.mapView convertPoint:point toCoordinateFromView:self.mapView]; 
    MKMapPoint mapPoint = MKMapPointForCoordinate(coord); 
    for (id overlay in self.mapView.overlays) 
    { 
     if ([overlay isKindOfClass:[MKPolygon class]]) 
     { 
      MKPolygon *poly = (MKPolygon*) overlay; 
      id view = [self.mapView viewForOverlay:poly]; 
      if ([view isKindOfClass:[MKPolygonView class]]) 
      { 
       MKPolygonView *polyView = (MKPolygonView*) view; 
       CGPoint polygonViewPoint = [polyView pointForMapPoint:mapPoint]; 
       BOOL mapCoordinateIsInPolygon = CGPathContainsPoint(polyView.path, NULL, polygonViewPoint, NO); 
       if (mapCoordinateIsInPolygon) { 
        debug(@"hit!") 
       } else { 
        debug(@"miss!"); 
       } 
      } 
     } 
    } 

}; 
[self.mapView addGestureRecognizer:tapInterceptor]; 

WildcardGestureRecognizer是在第一個鏈接的答案。調用mapView:viewForOverlay:不會很便宜,添加一個本地緩存將有所幫助。

+0

輝煌。這正是我在尋找疊加層時需要檢測的代碼。不過,我把它放在稱爲購買輕敲手勢識別器的方法裏面。沒有必要創建自定義攔截器,工作得很好。 – drekka

+0

This停止在iOS7上工作! polyView.path始終爲零! – Bach

+5

用MKPolygonRenderer替換MKPolygonView - 前者在iOS7中不推薦使用 – guyh92