iOS在使用原生地图MapKit的时候 会遇到点击锚点/标记点(MKAnnotationView
)的需求,但是会发现点击并没有实际方法/代理 可以响应点击事件,虽然官方文档中提供一个方法可以选中其标记点并让其置于最顶成,但是还是无法满足大部分自定义选中需求
[_chinaMapView selectAnnotation:tempMarker.pointAnnotation animated:YES]; //选中标记点 让其置于最顶
MapKit并不像谷歌地图 点击标记点可以响应其代理
- (BOOL)mapView:(GMSMapView *)mapView didTapMarker:(GMSMarker *)marker
因为iOS自带的MapKit框架没有其点击代理,首先解决思路是在viewForAnnotation代理中去做手势或者按钮 然后通过手势或者代理的Tag
- (MKAnnotationView *)mapView:(MKMapView *)mapview viewForAnnotation:(id <MKAnnotation>)annotation
但是发现在MKAnnotationView 上面添加的事件或者手势并不能响应 而是被MapView给响应了
解决方案
:去自定义一个AnnotationView继承MKAnnotationView
代码如下:
#import "HomeChinaAnnotationView.h"
@implementation HomeChinaAnnotationView
//如果监听到点击事件,就用 bringSubviewToFront 方法把self放在接收机的最前面,来接收这个事件。
- (UIView*)hitTest:(CGPoint)point withEvent:(UIEvent*)event
{
UIView *hitView = [super hitTest:point withEvent:event];
if (hitView != nil)
{
[self.superview bringSubviewToFront:self];
}
return hitView;
}
//此方法配合 - (UIView*)hitTest:(CGPoint)point withEvent:(UIEvent*)event; 方法使用,用于判断点击的point是否在自定一的callout view 的 bounds 之内。
- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent*)event
{
CGRect rect = self.bounds;
BOOL isInside = CGRectContainsPoint(rect, point);
if(!isInside)
{
for (UIView *view in self.subviews)
{
isInside = CGRectContainsPoint(view.frame, point);
if(isInside)
return isInside;
}
}
return isInside;
}
@end