Cli*_*lip 3 objective-c uibutton mkannotationview ios
我正在尝试使用自定义图像,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;
}
Run Code Online (Sandbox Code Playgroud)
小智 7
有两个主要问题:
frame自定义标注按钮没有被设置使得它基本上是不可见的.MKAnnotationView被创建,但其image属性(注释本身的形象-没有标注按钮的)未设置.这使得整个注释不可见.对于问题1,将按钮的框架设置为适当的值.例如:
UIImage *directionIcon = [UIImage imageNamed:@"IconDirections"];
directionButton.frame =
CGRectMake(0, 0, directionIcon.size.width, directionIcon.size.height);
Run Code Online (Sandbox Code Playgroud)
对于问题2,设置注释视图image(或创建MKPinAnnotationView代替):
annotationView.image = [UIImage imageNamed:@"SomeIcon"];
Run Code Online (Sandbox Code Playgroud)
此外,您应该通过更新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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2261 次 |
| 最近记录: |