要根据表格中的“可点击”标志来控制标注是否有附属按钮,我建议你在你的注解类中添加一个clickable属性,并在添加注解时设置它。然后在viewForAnnotation方法中创建注解视图的时候可以勾选这个属性。
要将注释添加到地图视图(即,当您调用 addAnnotation 时),如果您当前正在使用像 MKPointAnnotation 这样的预定义类,则需要定义自己的自定义类来实现MKAnnotation 协议。如果您已经有一个自定义类,请为其添加一个 clickable 属性。
这是一个自定义注释类的示例:
//CustomAnnotation.h...
@interface CustomAnnotation : NSObject<MKAnnotation>
@property (nonatomic, assign) CLLocationCoordinate2D coordinate;
@property (nonatomic, copy) NSString *title;
@property (nonatomic, copy) NSString *subtitle;
@property (nonatomic, assign) int annotationId;
@property (nonatomic, assign) BOOL clickable;
@end
//CustomAnnotation.m...
@implementation CustomAnnotation
@synthesize coordinate;
@synthesize title;
@synthesize subtitle;
@synthesize annotationId;
@synthesize clickable;
- (void)dealloc {
[title release];
[subtitle release];
[super dealloc];
}
@end
这是一个如何创建和添加注释的示例(注释属性的实际值将来自您的 sql 行):
CustomAnnotation *ca1 = [[CustomAnnotation alloc] init];
ca1.annotationId = 1;
ca1.coordinate = CLLocationCoordinate2DMake(lat1,long1);
ca1.title = @"clickable";
ca1.subtitle = @"clickable subtitle";
ca1.clickable = YES;
[myMapView addAnnotation:ca1];
[ca1 release];
CustomAnnotation *ca2 = [[CustomAnnotation alloc] init];
ca2.annotationId = 2;
ca2.coordinate = CLLocationCoordinate2DMake(lat2,long2);
ca2.title = @"not clickable";
ca2.subtitle = @"not clickable subtitle";
ca2.clickable = NO;
[myMapView addAnnotation:ca2];
[ca2 release];
那么viewForAnnotation 将如下所示:
-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
static NSString *reuseId = @"CustomAnnotation";
MKPinAnnotationView* customPinView = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:reuseId];
if (customPinView == nil) {
customPinView = [[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:reuseId] autorelease];
customPinView.pinColor = MKPinAnnotationColorPurple;
customPinView.animatesDrop = YES;
customPinView.canShowCallout = YES;
}
else {
customPinView.annotation = annotation;
}
CustomAnnotation *ca = (CustomAnnotation *)annotation;
if (ca.clickable)
customPinView.rightCalloutAccessoryView = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
else
customPinView.rightCalloutAccessoryView = nil;
return customPinView;
}
最后,您可以在calloutAccessoryControlTapped 委托方法中处理按钮按下并访问您的自定义注释的属性:
-(void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control
{
CustomAnnotation *ca = (CustomAnnotation *)view.annotation;
NSLog(@"annotation tapped, id=%d, title=%@", ca.annotationId, ca.title);
}