I’ve found some posts showing how to change the UIButton’s image or imageBackground depending on its state. But none of them mentioned the case where this UIButton is inside of a MKAnnotationView’s Callout bubble. Here is what I’m trying to do:
I have a lot of MKAnnotationViews on my map and I’d like the user to be able to set some of them as Favorites. And I think it should be cool if this option was available as an UIButton set as my 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];
}
}
I’ve tried different approaches. Is there any limitation for setting this particular state for UIButton inside the bubble ? Because UIControlStateHighlighted is working fine. I had to put that code on didSelectAnnotationView: ’cause if the annotation is already a favorite, the UIButton should appear in its selected state. What am I doing wrong?
Thanks to @Anna Karenina I discovered what I was doing wrong: using a single instance of my UIButton for all annotation views. I’ve done something a little different from her suggestion in viewForAnnotation though. Instead of storing “selected” state in my custom annotation class, I’m always checking if the annotation is currently inside my Array of Favorites and if it is, I change its button state to selected. Maybe her solution is more elegant and even faster, I’ll try it later.