在iOS地圖開發(fā)中,有時(shí)候我們需要在用戶點(diǎn)擊地圖空白處的時(shí)候執(zhí)行某些操作,例如隱藏地圖上的AnnotationView浮窗。類似百度地圖、高德地圖這樣的第三方SDK提供了點(diǎn)擊地圖空白處的方法,例如在百度地圖的SDK中有以下方法:
/**
*點(diǎn)中底圖空白處會(huì)回調(diào)此接口
*@param mapView 地圖View
*@param coordinate 空白處坐標(biāo)點(diǎn)的經(jīng)緯度
*/
- (void)mapView:(BMKMapView *)mapView onClickedMapBlank:(CLLocationCoordinate2D)coordinate;
但是在原生的MapKit中是沒有提供類似方法的,不過我們可以通過攔截觸摸事件的方式實(shí)現(xiàn),代碼如下:
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
UITouch *touch = [touches anyObject];
CGPoint point = [touch locationInView:self];
UIView *v = [self hitTest:point withEvent:event];
if ([v isKindOfClass: NSClassFromString(@"MKAnnotationContainerView")]) {
[self onClickedMapBlank];
NSLog(@"點(diǎn)擊空白區(qū)域");
} else if ([v isKindOfClass: NSClassFromString(@"MKAnnotationView")]) {
NSLog(@"點(diǎn)擊Annotation區(qū)域");
}
}
- (void)onClickedMapBlank{
//doSomething
}
把這些方法寫在一個(gè)繼承MKMapView的自定義view中,在onClickedMapBlank里做你想做的事吧。