MKAnnotationView drawRect: не вызывается

Я реализовал пользовательскую аннотацию, полученную из MKAnnotation, с именем ContainerAnnotation и пользовательское представление аннотации, полученное из MKAnnotationView, с помощью метода drawRect:, называемого ContainerAnnotationView. По какой-то причине метод 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: он отлично работает. Любая идея, что я делаю неправильно здесь?


person David Potter    schedule 30.08.2010    source источник


Ответы (2)


Проблема оказалась в том, что мой метод 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;
}
person David Potter    schedule 30.08.2010

Вы где-нибудь вызывали setNeedsDisplay для этого подкласса представления? (Сразу после того, как вы сделаете этот вид видимым, это хорошее место.)

person hotpaw2    schedule 30.08.2010
comment
Как вид становится видимым? Он становится видимым после возврата mapView:viewForAnnotation:? - person David Potter; 30.08.2010
comment
Я спрашиваю, потому что не вижу кода для других представлений аннотаций, который явно делает их видимыми. Нигде они не вызывают setNeedsDisplay. - person David Potter; 30.08.2010