11

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

私のView Controllerから:

- (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 を実装していない別のカスタム注釈ビューもあります。これは正常に動作します。ここで何が間違っているのか分かりますか?

4

2 に答える 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;
}
于 2010-08-30T21:08:40.870 に答える
2

このビュー サブクラスの setNeedsDisplay をどこかで呼び出しましたか? (このビューを表示した直後が良い場所です。)

于 2010-08-30T17:05:00.997 に答える