当我使用以下代码时,我试图在MKAnnotationView
上使用自定义图像我的注释中没有图像。我已经检查了调试,以确保图像正确加载到UIImage
。
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation {
MKAnnotationView *annotationView = [mapView dequeueReusableAnnotationViewWithIdentifier:@"String"];
if(!annotationView) {
annotationView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"String"];
UIButton *directionButton = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage *directionIcon = [UIImage imageNamed:@"IconDirections"];
[directionButton setImage:directionIcon forState:UIControlStateNormal];
annotationView.rightCalloutAccessoryView = directionButton;
}
annotationView.enabled = YES;
annotationView.canShowCallout = YES;
return annotationView;
}
答案 0 :(得分:7)
有两个主要问题:
frame
,使其基本上不可见。MKAnnotationView
,但未设置其image
属性(注释本身的图像 - 而不是标注按钮&#39})。这使得整个注释不可见。对于问题1,将按钮的框架设置为适当的值。例如:
UIImage *directionIcon = [UIImage imageNamed:@"IconDirections"];
directionButton.frame =
CGRectMake(0, 0, directionIcon.size.width, directionIcon.size.height);
对于问题2,请设置注释视图image
(或改为创建MKPinAnnotationView
):
annotationView.image = [UIImage imageNamed:@"SomeIcon"];
此外,您应该通过更新annotation
属性来正确处理视图重用
完整的例子:
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
MKAnnotationView *annotationView = [mapView dequeueReusableAnnotationViewWithIdentifier:@"String"];
if(!annotationView) {
annotationView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"String"];
annotationView.image = [UIImage imageNamed:@"SomeIcon"];
UIButton *directionButton = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage *directionIcon = [UIImage imageNamed:@"IconDirections"];
directionButton.frame =
CGRectMake(0, 0, directionIcon.size.width, directionIcon.size.height);
[directionButton setImage:directionIcon forState:UIControlStateNormal];
annotationView.rightCalloutAccessoryView = directionButton;
annotationView.enabled = YES;
annotationView.canShowCallout = YES;
}
else {
//update annotation to current if re-using a view
annotationView.annotation = annotation;
}
return annotationView;
}
答案 1 :(得分:0)
为了显示标注,必须选择注释。要以编程方式执行此操作,请致电:
[mapView selectAnnotation:annotation animated:YES];
其中annotation
是您要为其显示标注的特定MKAnnotation
。
你几乎肯定想把它放在- (void)mapView:(MKMapView *)mapView didAddAnnotationViews:(NSArray *)views
。
有一些需要考虑的注意事项,所以这里有另外两篇文章有一些很好的答案和相关的讨论: