一、背景描述:
使用的苹果自带的地图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];
}
}
}
}
好了