0

我正在使用以下代码

-(MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
    if ([[annotation title] isEqualToString:@"Current Location"] )
    {
        MKAnnotationView *anView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"currentPin"];

        anView.image = [UIImage imageNamed:@"pin_green.png"];
        anView.canShowCallout = true;
        anView.enabled = true;
        return anView;
    }

问题是,它随机消失并再次出现。给用户带来非常糟糕的体验。有任何解决这个问题的方法吗?

4

2 回答 2

0

您应该使用 MKMapViewdequeueReusableAnnotationViewWithIdentifier:并查看在创建新视图之前是否获得了视图initWithAnnotation:reuseIdentifier:

MKAnnotationView *anView = [mapView dequeueReusableAnnotationViewWithIdentifier:@"currentPin"];

if (!anView) {
    anView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"currentPin"];

    anView.image = [UIImage imageNamed:@"pin_green.png"];
    anView.canShowCallout = true;
    anView.enabled = true;
}

return anView;

也就是说,我不完全确定这是您问题的原因。

于 2013-04-15T18:01:30.960 回答
0

这段代码有几个可疑的地方:

  • dequeue正如有人指出的那样,您没有使用。特别是,这里的问题是您每次都在创建一个新视图,而不是检查是否需要创建一个新视图。

  • 您忘记了关键步骤,即将视图与注释相关联。

这是一个简单viewForAnnotation:实现的规范结构,我们提供自己的视图:

- (MKAnnotationView *)mapView:(MKMapView *)mapView
            viewForAnnotation:(id <MKAnnotation>)annotation {
    MKAnnotationView* v = nil;
    if ([annotation.title isEqualToString:@"Current Location"]) {
        static NSString* ident = @"greenPin";
        v = [mapView dequeueReusableAnnotationViewWithIdentifier:ident];
        if (v == nil) {
            v = [[MKAnnotationView alloc] initWithAnnotation:annotation
                                              reuseIdentifier:ident];
            v.image = [UIImage imageNamed:@"pin_green.png"];
            v.canShowCallout = YES;
        }
        v.annotation = annotation;
    }
    return v;
}

由于该代码对我有用,我建议您从它开始并根据需要对其进行调整。

顺便说一句,你不需要这个方法只是为了得到一个绿色的别针!你知道的,对吧?iOS 会给你一个绿色的别针 (MKPinAnnotationColorGreen)。

于 2013-04-15T18:12:19.313 回答