2012-03-14 16 views
11

這是我想要的 - 用戶在地圖上點擊,我的代碼被執行,然後系統代碼被執行(如果用戶點擊註釋標註出現等)。我怎樣才能抓住MapView,然後將它傳遞給默認的手勢識別器?

我添加簡單的點擊識別到地圖視圖:

UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(mapViewTapped:)]; 
[self.mapView addGestureRecognizer:tapGestureRecognizer]; 
[tapGestureRecognizer release]; 

裏面mapViewTapped我的代碼被執行。現在我想通知系統的點擊代碼(例如顯示標註)。我怎麼做?如何傳遞我攔截的事件?

回答

23

的方法之一是實現UIGestureRecognizerDelegate方法gestureRecognizer:shouldRecognizeSimultaneouslyWithGestureRecognizer:並在它返回YES

//add <UIGestureRecognizerDelegate> to .h to avoid compiler warning 

//add this where you create tapGestureRecognizer... 
tapGestureRecognizer.delegate = self; 

-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer 
    shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer 
{ 
    return YES; 
} 

現在你mapViewTapped:將被調用,然後在地圖視圖的識別器將調用它的方法。如果點擊位於註釋視圖上,則地圖視圖將顯示其標註(如果已實施,則會調用didSelectAnnotationView委託方法)。


另一種方式,如果你需要更多的控制,那麼不要做上述情況,在你mapViewTapped:您可以檢查是否水龍頭是在一個註解視圖,然後手動選擇註釋然後將展示其標註(和調用didSelectAnnotationView委託方法):

-(void)mapViewTapped:(UITapGestureRecognizer *)tgr 
{ 
    CGPoint p = [tgr locationInView:mapView]; 

    UIView *v = [mapView hitTest:p withEvent:nil]; 

    id<MKAnnotation> ann = nil; 

    if ([v isKindOfClass:[MKAnnotationView class]]) 
    { 
     //annotation view was tapped, select it... 
     ann = ((MKAnnotationView *)v).annotation; 
     [mapView selectAnnotation:ann animated:YES]; 
    } 
    else 
    { 
     //annotation view was not tapped, deselect if some ann is selected... 
     if (mapView.selectedAnnotations.count != 0) 
     { 
      ann = [mapView.selectedAnnotations objectAtIndex:0]; 
      [mapView deselectAnnotation:ann animated:YES]; 
     } 
    } 
} 
+0

謝謝你,你的解釋不僅是有益的,而且非常詳細 – MegaManX 2012-03-14 13:54:45

+1

非常感謝,你的第二個建議是什麼我了! – MrDB 2012-04-14 06:58:42

+0

偉大的建議,是我正在尋找 – 2014-04-03 16:21:29

相關問題