I've implemented a custom annotation derived from MKAnnotation called ContainerAnnotation and a custom annotation view derived from MKAnnotationView with a drawRect: method called ContainerAnnotationView. For some reason the drawRect: method is not getting called and I can't figure out why.
Here's the source code for my annotation view.
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
From my 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...
}
I have other annotations that use a vanilla MKAnnotation with an image that work fine. I also have another custom annotation view that doesn't implement drawRect: that works fine. Any idea what I'm doing wrong here?
The problem turned out to be that my drawRect: method was never being called because the frame was not set to a non-zero size. Adding an initWithAnnotation: method to do this solved the problem.
- (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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With