ios-mapkit, странное поведение с пользовательскими аннотациями изображений

Я написал код для отображения аннотаций с пользовательскими изображениями в режиме просмотра карты. Мой делегат mapview реализует этот метод для настройки аннотаций, когда они помещаются на карту:

- (MKAnnotationView *) mapView:(MKMapView *) mapView viewForAnnotation:(id<MKAnnotation>) annotation {
if ([annotation isKindOfClass:[Station class]]) {
    Station *current = (Station *)annotation;
    MKPinAnnotationView *customPinview = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:nil];
    if([[current type] compare:FONTANELLA]==NSOrderedSame)
        customPinview.pinColor = MKPinAnnotationColorPurple;
    else{
        int test=current.bici;
        if(test==0)
            customPinview.image = [UIImage imageNamed:@"bicimir.png"];
        else if(test<4)
            customPinview.image = [UIImage imageNamed:@"bicimi.png"];
        else if(test>=4)
            customPinview.image = [UIImage imageNamed:@"bicimig.png"];
    }
    customPinview.animatesDrop = NO;
    customPinview.canShowCallout = YES;
    return customPinview;
}
else{
    NSString *identifier=@"MyLocation";
    MKPinAnnotationView *annotationView = (MKPinAnnotationView *) [_mapView dequeueReusableAnnotationViewWithIdentifier:identifier];
    return annotationView;
}

}

Проблема заключается в странном поведении, когда я долго нажимаю на пользовательскую аннотацию на карте: изменяется изображение и отображается красный значок по умолчанию.

Почему такое поведение? И как этого избежать?


person Matteo    schedule 11.11.2011    source источник


Ответы (2)


Если вы хотите использовать собственное изображение для представления аннотации, создайте общий MKAnnotationView вместо MKPinAnnotationView.

MKPinAnnotationView действительно любит отображать свое изображение по умолчанию, которое является булавкой.

Немного измените логику, чтобы для FONTANELLA она создавала MKPinAnnotationView, а для остальных - MKAnnotationView.

Кроме того, вам действительно следует реализовать повторное использование представления аннотации для всех случаев (и последняя часть else не имеет смысла, поскольку ничего не делается, если удаление из очереди ничего не возвращает - вместо этого вы можете просто сделать return nil;).

person Community    schedule 11.11.2011
comment
Спасибо за ответ! это очень полезно - person Matteo; 12.11.2011

внутри файла .h

@interface AddressAnnotation : NSObject<MKAnnotation> {
    CLLocationCoordinate2D coordinate;
    NSString *mPinColor;

}

@property (nonatomic, retain) NSString *mPinColor;

@end

в файле .m

@implementation AddressAnnotation

@synthesize coordinate mPinColor;


- (NSString *)pincolor{
    return mPinColor;
}

- (void) setpincolor:(NSString*) String1{
    mPinColor = String1;
}


-(id)initWithCoordinate:(CLLocationCoordinate2D) c{
    coordinate=c;
    NSLog(@"%f,%f",c.latitude,c.longitude);
    return self;
}
@end

внутри файла класса .m

- (MKAnnotationView *) mapView:(MKMapView *)mapView1 viewForAnnotation:(AddressAnnotation *) annotation{

    UIImage *anImage=[[UIImage alloc] init];

MKAnnotationView *annView=(MKAnnotationView*)[mapView1 dequeueReusableAnnotationViewWithIdentifier:@"annotation"];

    if(annView==nil)
    {
        annView=[[[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"annotation"] autorelease];

    }

    if([annotation.mPinColor isEqualToString:@"green"])
    {

        anImage=[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Google pin green.png" ofType:nil]];
    }
    else if([annotation.mPinColor isEqualToString:@"red"])
    {
        anImage=[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Google pin red.png" ofType:nil]];
    }
    else if([annotation.mPinColor isEqualToString:@"blue"])
    {
        anImage=[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Google pin blue.png" ofType:nil]];
    }

    annView.image = anImage;

    return annView;

}
person Anil Kothari    schedule 18.11.2011