每个引脚的不同自定义图像

时间:2014-08-07 14:10:43

标签: ios mapkit mkannotationview

这听起来像是一般性的问题,但如果我想要所有针脚的相同图像,我只能找到答案,我不会这样做。

这就是我现在的工作方式:

我的所有位置都在一个Locations数组中(自定义类包含long,lat,name,pin name)。

在viewdidLoad中我循环该数组并使用找到的每个对象创建我的引脚,请参阅以下代码:

     for(int i = 0 ; i<[_locationList count] ; i++)
        {
        Location *item = [_locationList objectAtIndex:i];
        CLLocationCoordinate2D coordinate;
        coordinate.latitude = item.locationLatitude;
        coordinate.longitude = item.locationLongitude;
        NSString *title = item.locationName;
        CustomAnnotation* ann = [CustomAnnotation new];
        ann.name = title;
        ann.coordinate = coordinate;
        ann.pinName = [NSString stringWithFormat:@"pin%i.png",item.idPin];
        [self.map addAnnotation:ann];
    }

这很简单,部分来自CustomAnnotation类,它是以下代码:

@interface CustomAnnotation : MKPointAnnotation <MKAnnotation>{

}

@property (nonatomic, retain) NSString *name;
@property (nonatomic, retain) NSString *description;
@property (nonatomic, retain) NSString *pinName;


@end

这一切都来自我在互联网上看到过的东西,我相信这一切都是正确的。

在我看来,我仍然会创建非常经典的引脚,它们只有一个属性(pinName),这就是为什么它来自自定义类。

现在,在viewForAnnotation中,我绝对没有IDEA如何告诉它获取该pinName并使用它。

- (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:[MKPointAnnotation 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.canShowCallout = YES;
            pinView.image = // I wanted to write annotation.pinName But it's just not that.
            pinView.calloutOffset = CGPointMake(0, 32);

             }else {
            pinView.annotation = annotation;
        }
        return pinView;
    }
    return nil;
}

我错过了什么?我显然做错了什么,但我不能解决这个问题,而且我仍然对MKAnnotationsView&amp; amp;和MKAnnotationsView&amp; MKPointAnnotation&amp; MKPinAnnotation,......

更多信息:引脚名称是&#34; pinX.png&#34;,X是介于1和12之间的数字。我只想使用该名称,以便程序可以在图片所在的资源中找到它。

1 个答案:

答案 0 :(得分:2)

由于您的注释类型为CustomAnnotation,因此检查注释是否属于MKPointAnnotation更为准确。

然后,将annotation参数转换为自定义类,可以让您轻松访问其中的自定义属性:

CustomAnnotation *ca = (CustomAnnotation *)annotation;
pinView.image = [UIImage imageNamed:ca.pinName];

但是,因为每个注释的图像可能不同,所以您应该在创建注释视图后将其设置为(不仅仅是{{1}阻止 - 否则注释最终可能会重新使用另一个注释中的视图不再可见,并且将显示错误的图像。

更新的方法如下所示:

if (!pinView)


有关MapKit类之间差异的混淆,请参阅: