1. 程式人生 > >MKMapView父控制元件攔截子控制元件點選時的解決辦法

MKMapView父控制元件攔截子控制元件點選時的解決辦法

一、背景描述:

使用的蘋果自帶的地圖SDK(MKMapView),需求需要在點選地圖空白頁面的時候,氣泡變為不選中的狀態,並且收起底部的卡片。

所以在地圖上面增加了手勢,程式碼如下:

    self.mapView = [[MKMapView alloc] initWithFrame:self.view.bounds];
    self.mapView.mapType = MKMapTypeStandard;
    self.mapView.delegate = self;
    self.mapView.rotateEnabled = NO;
    [self.view addSubview:self.mapView];
    UITapGestureRecognizer *mTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapPress:)];
    mTap.delegate = self;
    [self.view addGestureRecognizer:mTap];
    [self.mapView tn_pinEdgesToSuperviewEdges];
- (void)tapPress:(id)sender
{
    for (TNHotelMapPointAnnotation *annotation in self.annotatons) {
        if(annotation.isSelected)
        {
            [self.mapView removeAnnotation:annotation];
            annotation.isSelected = NO;
            [self.mapView addAnnotation:annotation];
        }
    }
    //移動地圖呼叫此方法
    if(DELEGATE_HAS_METHOD(moveMapController:))
    {
        [self.delegate moveMapController:self];
    }
}

但是出現一個現象,點選選中的氣泡(黃色)會變成未選中(綠色)後,再次變為選中大哭

正常來說應該是始終是選中的狀態(黃色)。

二、解決過程:

debug發現,每次點選氣泡的時候,都是先走的手勢方法,然後走的點選氣泡的代理方法,這是事件響應的傳遞原理,那麼問題來了,怎麼解決????奮鬥

三、解決方法:

嘗試了很多種方法,解決方法如下:

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    if ([NSStringFromClass([touch.view.superview class]) isEqualToString:@"TNHotelMapCustomAnnotationView"]) {
        return NO;
    }
    return  YES;
}

並且附上選中氣泡的代理方法程式碼:

- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view
{
    if ([view.annotation isKindOfClass:[TNHotelMapPointAnnotation class]]) {
        TNHotelMapPointAnnotation *lastAnnotation = (TNHotelMapPointAnnotation *)view.annotation;
        //處理選中與選中狀態的資料
        for (TNHotelMapPointAnnotation *annotation in self.annotatons) {
            if((TNHotelMapPointAnnotation *)view.annotation == annotation)
            {
                if(!annotation.isSelected)
                {
                    [self.mapView removeAnnotation:annotation];
                    annotation.isSelected = YES;
                    [self.mapView addAnnotation:annotation];
                }
            }else
            {
                if(annotation.isSelected)
                {
                    [self.mapView removeAnnotation:annotation];
                    annotation.isSelected = NO;
                    [self.mapView addAnnotation:annotation];
                }
            }
        }
}

大笑好了