MKAnnotationView drawRect:没有被调用
问题描述:
我已经实现了一个名为ContainerAnnotation的MKAnnotation派生的自定义注释和一个名为ContainerAnnotationView的drawRect:方法派生自MKAnnotationView的自定义注解视图。出于某种原因,drawRect:方法没有被调用,我找不到原因。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...
}
我有使用一个V其他注释anilla MKAnnotation与一个图像,工作正常。我也有另一个不实现drawRect的自定义注释视图:工作正常。任何想法我在这里做错了吗?
答
问题原来是我的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;
}
答
您是否在任何地方为此视图子类调用了setNeedsDisplay? (刚才你让这个视图可见是个好地方。)
视图如何变得可见?在mapView:viewForAnnotation之后它是否可见:返回? – 2010-08-30 17:47:27
我问,因为我没有看到明确使其可见的其他注释视图的任何代码。无处他们叫setNeedsDisplay。 – 2010-08-30 18:24:03
这就是我需要的所有工作。 – VaporwareWolf 2014-04-16 20:39:20