当前位置 : 主页 > 手机开发 > ios >

ios – MKAnnotationView自定义按钮图像

来源:互联网 收集:自由互联 发布时间:2021-06-11
当我使用以下代码时,我试图在我的MKAnnotationView上使用自定义图像,我的注释上没有图像.我已经检查了调试以确保图像正确加载到UI Image中. - (MKAnnotationView *)mapView:(MKMapView *)mapView viewFor
当我使用以下代码时,我试图在我的MKAnnotationView上使用自定义图像,我的注释上没有图像.我已经检查了调试以确保图像正确加载到UI Image中.

- (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;
}
有两个主要问题:

>未设置自定义标注按钮的框架,使其基本上不可见.
>正在创建MKAnnotationView,但未设置其图像属性(注释本身的图像 – 而不是标注按钮).这使得整个注释不可见.

对于问题1,将按钮的框架设置为适当的值.例如:

UIImage *directionIcon = [UIImage imageNamed:@"IconDirections"];
directionButton.frame = 
    CGRectMake(0, 0, directionIcon.size.width, directionIcon.size.height);

对于问题2,设置注释视图的图像(或创建MKPinAnnotationView):

annotationView.image = [UIImage imageNamed:@"SomeIcon"];

此外,您应该通过更新注释属性来正确处理视图重用.
完整的例子:

- (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;
}
网友评论