MKAnnotationView的drawRect方法没有被调用

11
我实现了一个自定义注释(ContainerAnnotation),它派生自MKAnnotation,以及一个带有drawRect:方法的自定义注释视图(ContainerAnnotationView),后者派生自MKAnnotationView。但是,我无法弄清楚为什么drawRect:方法没有被调用。
下面是我注释视图的源代码。
ContainerAnnotationView.h:
@interface ContainerAnnotationView : MKAnnotationView
{
}

@end

ContainerAnnotationView.m:

@implementation ContainerAnnotationView

- (void) drawRect: (CGRect) rect
{
    // Draw the background image.
    UIImage * backgroundImage = [UIImage imageNamed: @"container_flag_large.png"];
    CGRect annotationRectangle = CGRectMake(0.0f, 0.0f, backgroundImage.size.width, backgroundImage.size.height);
    [backgroundImage drawInRect: annotationRectangle];

    // Draw the number of annotations.
    [[UIColor whiteColor] set];
    UIFont * font = [UIFont systemFontOfSize: [UIFont smallSystemFontSize]];
    CGPoint point = CGPointMake(2, 1);
    ContainerAnnotation * containerAnnotation = (ContainerAnnotation *) [self annotation];
    NSString * text = [NSString stringWithFormat: @"%d", containerAnnotation.annotations.count];
    [text drawAtPoint: point withFont: font];
}

@end

从我的视图控制器中:

- (MKAnnotationView *) mapView: (MKMapView *) mapView viewForAnnotation: (id <MKAnnotation>) annotation
{

    if ([annotation isKindOfClass: [ContainerAnnotation class]])
    {
        ContainerAnnotationView * annotationView = (ContainerAnnotationView *)[_mapView dequeueReusableAnnotationViewWithIdentifier: _containerMapAnnotationId];
        if (annotationView == nil)
        {
            annotationView = [[[ContainerAnnotationView alloc] initWithAnnotation: annotation reuseIdentifier: _containerMapAnnotationId] autorelease];     
            annotationView.centerOffset = CGPointMake(0, -17.5);
            annotationView.rightCalloutAccessoryView = [UIButton buttonWithType: UIButtonTypeDetailDisclosure];
            annotationView.canShowCallout = YES;
        }
        annotationView.annotation = annotation;

        return annotationView;
    }
    // etc...
}

我有其他使用普通MKAnnotation和图像的注释,它们可以正常工作。我还有另一个自定义注释视图,它没有实现drawRect:,但也可以正常工作。你有什么想法,我在这里做错了什么?

2个回答

23
问题的原因是我的drawRect:方法从未被调用,因为框架大小未设置为非零值。通过添加一个initWithAnnotation:方法来解决这个问题。
- (id) initWithAnnotation: (id <MKAnnotation>) annotation reuseIdentifier: (NSString *) reuseIdentifier
{
    self = [super initWithAnnotation: annotation reuseIdentifier: reuseIdentifier];
    if (self != nil)
    {
        self.frame = CGRectMake(0, 0, 30, 30);
        self.opaque = NO;
    }
    return self;
}

2
你是否在该视图子类中调用了setNeedsDisplay方法?(在该视图可见后立即调用是一个好的时机。)

视图是如何变得可见的?它是在mapView:viewForAnnotation:返回后变得可见的吗? - David Potter
我问这个问题是因为我没有看到其他标注视图的任何明确使它们可见的代码。它们没有调用setNeedsDisplay方法。 - David Potter

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接