将MKAnnotationViews设置为收藏夹

时间:2012-12-12 03:48:44

标签: ios uibutton mkannotationview

我发现了一些帖子,展示了如何根据状态更改UIButton的图像或imageBackground。但他们都没有提到这个UIButton在MKAnnotationView的Callout气泡中的情况。这是我正在尝试做的事情:

我的地图上有很多MKAnnotationViews,我希望用户能够将其中一些设置为收藏夹。我认为如果UIButton设置为我的leftCalloutAccessoryView,此选项可以很酷。

- (MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation {
// Here I've created the button...
// Now I set the states:

        [self.button setImage:self.image_1 forState:UIControlStateNormal];
        [self.button setImage:self.image_2 forState:UIControlStateHighlighted];
        [self.button setImage:self.image_3 forState:UIControlStateSelected];

        annotationView.leftCalloutAccessoryView = self.button;
}

- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control
{
self.button.selected = YES;
}

- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view
{
if ([self annotationIsFavorite:view.annotation])
{
    [self.button setImage:self.image_3 forState:UIControlStateNormal];
}
}

我尝试了不同的方法。在泡沫中为UIButton设置此特定状态是否有任何限制?因为UIControlStateHighlighted工作正常。我必须将该代码放在didSelectAnnotationView:'上,因为如果注释已经是收藏夹,UIButton应该出现在其选定状态。我做错了什么?

1 个答案:

答案 0 :(得分:1)

感谢@Anna Karenina我发现了我做错了什么:使用我的UIButton的单个实例来获取所有注释视图。我在viewForAnnotation中做了一些与她的建议略有不同的事情。我没有在我的自定义注释类中存储“选定”状态,而是总是检查注释当前是否在我的收藏夹数组中,如果是,我将其按钮状态更改为选中状态。也许她的解决方案更优雅,更快,我稍后会尝试。