我有一类Picture
,其中包含每个位置的latitude
和longitude
以及image
。我想将它们作为注释添加到MapView
并显示其图像而不是针对这些位置的图钉。
我有一个自定义注释:
@interface Annotation : MKAnnotationView <MKAnnotation>
@property (nonatomic,assign) CLLocationCoordinate2D coordinate;
@property (nonatomic,copy) NSString *title;
@property (nonatomic,copy) NSString *subtitle;
@property (nonatomic,retain) UIImage *image;
@end
和
@implementation Annotation
@synthesize title,subtitle,coordinate,image;
@end
现在在主要代码中我正在尝试这个:
CLLocationCoordinate2D location;
Annotation *myAnn;
for(Pictures *pic in picturesFromDB)
{
myAnn = [[Annotation alloc] init];
location.latitude = [pic.langT doubleValue];
location.longitude = [pic.longT doubleValue];
myAnn.coordinate = location;
myAnn.title = pic.descript;
myAnn.image = [UIImage imageWithData:pic.image]; //Not sure about this line!
[self.mapView addAnnotation:myAnn];
}
我是否还需要委托,必须调用“viewForAnnotation”?因为它不起作用,我为代表做了这个:
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
// If it's the user location, just return nil.
if ([annotation isKindOfClass:[MKUserLocation class]])
return nil;
// Handle any custom annotations.
if ([annotation isKindOfClass:[Annotation class]])
{
// Try to dequeue an existing pin view first.
MKAnnotationView *pinView = (MKAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:@"CustomPinAnnotationView"];
if (!pinView)
{
// If an existing pin view was not available, create one.
pinView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"CustomPinAnnotationView"];
//pinView.animatesDrop = YES;
pinView.canShowCallout = YES;
pinView.image = [UIImage imageNamed:@"image.png"];
pinView.calloutOffset = CGPointMake(0, 4);
} else {
pinView.annotation = annotation;
}
return pinView;
}
return nil;
}
这样可以正常工作但是将相同的图像添加到所有位置。但我有一个特定的图片,而不是每个位置的image.png
。
位置数量是可变的,也是动态的。
如何将该图像传递给代理人。我试图在传递的注释中找到图像字段,但它不存在!我很感激任何建议。
答案 0 :(得分:2)
您需要将注释强制转换为自定义类,以便可以访问其属性 -
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
// Handle any custom annotations.
if ([annotation isKindOfClass:[Annotation class]])
{
Annotation *myAnn=(Annotation *)annotation;
// Try to dequeue an existing pin view first.
MKAnnotationView *pinView = (MKAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:@"CustomPinAnnotationView"];
if (!pinView)
{
// If an existing pin view was not available, create one.
pinView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"CustomPinAnnotationView"];
//pinView.animatesDrop = YES;
pinView.canShowCallout = YES;
pinView.calloutOffset = CGPointMake(0, 4);
} else {
pinView.annotation = annotation;
}
pinView.image = myAnn.image;
return pinView;
}
return nil;
}