MKAnnotationView自定义按钮图像

时间:2014-06-15 00:10:04

标签: ios objective-c uibutton mkannotationview

当我使用以下代码时,我试图在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;
}

2 个答案:

答案 0 :(得分:7)

有两个主要问题:

  1. 未设置自定义标注按钮的frame,使其基本上不可见。
  2. 正在创建MKAnnotationView,但未设置其image属性(注释本身的图像 - 而不是标注按钮&#39})。这使得整个注释不可见。
  3. 对于问题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

有一些需要考虑的注意事项,所以这里有另外两篇文章有一些很好的答案和相关的讨论: