可可触摸-MapKit更新注释图像



在异步请求完成并包含有关注释状态的信息后,我在查找更新自定义MKAnnotationView映像的方法时遇到问题。到目前为止,我有这个:

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation {
    static NSString *identifier = @"EstacionEB";   
    if ([annotation isKindOfClass:[EstacionEB class]]) {
        EstacionEB *location = (EstacionEB *) annotation;
        CustomPin *annotationView = (CustomPin *) [_mapita dequeueReusableAnnotationViewWithIdentifier:identifier];
        if (annotationView == nil) {
            annotationView = [[CustomPin alloc] initWithAnnotation:annotation reuseIdentifier:identifier];
        } else {
            annotationView.annotation = annotation;
        }
        UIImage * image = [UIImage imageNamed:[NSString stringWithFormat:@"%@.png", [location elStatus]]];
        annotationView.enabled = YES;
        annotationView.canShowCallout = YES;
        annotationView.image = image;
        NSDictionary *temp = [[NSDictionary alloc] 
                              initWithObjects:[NSArray arrayWithObjects:annotationView, location, nil]
                              forKeys:[NSArray arrayWithObjects:@"view", @"annotation", nil]
                              ];
        //This array is synthesized and inited in my controller's viewDidLoad
        [self.markers setObject:temp forKey:location.eid];
        return annotationView;
    }
    return nil;    
}

过了一会儿,我做了一个请求,得到了一个NSDictionary结果,我试图做以下操作,它会向两个元素返回null:

- (void)updateStation:(NSString *)eid withDetails:(NSDictionary *)details
{
    NSInteger free = [details objectForKey:@"free"];
    NSInteger parkings = [details objectForKey:@"parkings"];
    NSDictionary *storedStations = [self.markers objectForKey:eid];
    CustomPin *pin = [storedStations objectForKey:@"view"]; //nil
    EstacionEB *station = [referencia objectForKey:@"annotation"]; //nil as well
    [station setSubtitle:free];
    NSString *status;
    if( free==0 ){
        status = @"empty";
    } else if( (free.intValue>0) && (parkings.intValue<=3)  ){
        status = @"warning";
    } else {
        status = @"available";
    }
    UIImage * image = [UIImage imageNamed:[NSString imageWithFormat:@"%@.png", status]];
    pin.image = image;
}

这不会带来任何错误(假设我正确地粘贴和诋毁了所有内容(,但NSMutableDictionary应该包含我的自定义MKAnnotationView和MKAnnotation,但即使我在请求完成之前将它们全部记录下来,并且它显示正确,当请求完成时,就好像MKAnnotatonView和MKAnnotation都不是我所期望的一样,因此,我无法修改注释以更改图像或更新注释视图。

任何想法都将不胜感激!

我不知道为什么要从标记数组中获得零值(尤其是注释(。但是,我不建议像那样存储对注释视图的引用。

viewForAnnotation委托方法可以在地图视图认为必要的任何时候被调用,并且视图对象可以从一个调用更改为下一个调用。由于您也在为每个注释使用相同的重用标识符来重新使用注释视图,因此以后也有可能为另一个注释重新使用相同的视图对象。

相反,在updateStation中,我建议如下:

  • 循环浏览地图视图的annotations阵列
  • 如果注释的类型为EstacionEB,则检查其eid是否与正在更新的类型匹配
  • 更新注释的subTitleelStatus属性(更新elStatus很重要,因为viewForAnnotation委托方法使用它来设置图像(
  • 通过调用映射视图的viewForAnnotation:实例方法获取注释的当前视图(这与委托方法mapView:viewForAnnotation:相同,是而不是(
  • 更新视图的image属性

请参阅其他相关问题以获取类似的示例。

最新更新