具有自定义视图和图像视图的MKAnnotationView

在我的地图应用程序,而不是显示一个别针,我想显示一个彩色的背景圆形图像。 背景的颜色(下面的图像是绿色的阴影)是dynamic的。 它将如下图所示:

在这里输入图像说明

我创build了TCircleView在“drawRect”中绘制颜色

为了显示类似的注释,我创build了TCircleView和UIImageView的对象,并将它们添加到MKAnnotationView对象中。 它看起来不错,如预期般可见。

但它不允许检测点击/触摸来显示呼叫。

我使用下面的代码:

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation { if ([annotation isKindOfClass:[MKPointAnnotation class]]) { return nil; } static NSString *annotationIdentifier = @"StickerPin"; MKAnnotationView *annotationView = (MKAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:annotationIdentifier]; if (!annotationView) { annotationView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:annotationIdentifier]; annotationView.canShowCallout = YES; } TCircleView* circleView = [[TCircleView alloc] init]; circleView.green = [postObj[@"severity"] floatValue]; //dynamic value coming from server UIImageView* imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Piano"]]; CGRect r = imgView.frame; r.size.height = r.size.width = 60; imgView.frame = r; circleView.frame = r; [annotationView addSubview:circleView]; [annotationView addSubview:imgView]; return annotationView; } 

它不允许显示标注,甚至不会调用委托“didSelectAnnotationView:”
如何在地图上显示自定义视图作为注释?

MKAnnotationView的默认帧widthheight是0,0。
这很可能阻止它响应触摸。

通常情况下,如果您设置其image属性, frame会自动为您设置。

由于您不是设置image并添加子视图,所以请尝试手动将frame设置为至less与其最大的子视图一样大。

例如:

 imgView.frame = r; circleView.frame = r; annotationView.frame = r; // <-- add this line 

我创build了一个注解视图的子类,并实现了它。 代码如下:

 @interface TStickerAnnotationView : MKAnnotationView @property(nonatomic) float stickerColor; @end @interface TStickerAnnotationView () { UIImageView *_imageView; TCircleView *_circleView; } @end @implementation TStickerAnnotationView - (id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { // make sure the x and y of the CGRect are half it's // width and height, so the callout shows when user clicks // in the middle of the image CGRect viewRect = CGRectMake(-30, -30, 60, 60); TCircleView* circleView = [[TCircleView alloc] initWithFrame:viewRect]; _circleView = circleView; [self addSubview:circleView]; UIImageView* imageView = [[UIImageView alloc] initWithFrame:viewRect]; // keeps the image dimensions correct // so if you have a rectangle image, it will show up as a rectangle, // instead of being resized into a square imageView.contentMode = UIViewContentModeScaleAspectFit; _imageView = imageView; [self addSubview:imageView]; } return self; } - (void)setImage:(UIImage *)image { // when an image is set for the annotation view, // it actually adds the image to the image view _imageView.image = image; } - (void)stickerColor:(float)color { _circleView.green = color; [_circleView setNeedsDisplay]; } 

试着看看这个解决scheme – 我发现它相关http://blog.jaanussiim.com/2014/01/28/floating-annotations.html