问题
I have a UIAlertView which appears as a confirmation when a user wants to delete a RegionAnnotation.
I'm having trouble figuring out how to access the RegionAnnotationView that called the UIAlertView which I need in order to delete the RegionAnnotation.
Here's my broken code - you can see where I'm trying to cast the AlertView's superview into a RegionAnnotationView (an admittedly bad idea).
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if(buttonIndex==0)
{
NSLog(@"alertView.superview is a %@",alertView.superview);
RegionAnnotationView *regionView = (RegionAnnotationView *)alertView.superview;
RegionAnnotation *regionAnnotation = (RegionAnnotation *)regionView.annotation;
[self.locationManager stopMonitoringForRegion:regionAnnotation.region];
[regionView removeRadiusOverlay];
[self.mapView removeAnnotation:regionAnnotation];
}
}
回答1:
Since the annotation is selected before the user can delete it, you can get a reference to the annotation from the map view's selectedAnnotations
property.
In the alert view delegate method, you can do something like this:
if (mapView.selectedAnnotations.count == 0)
{
//shouldn't happen but just in case
}
else
{
//since only one annotation can be selected at a time,
//the one selected is at index 0...
RegionAnnotation *regionAnnotation
= [mapView.selectedAnnotations objectAtIndex:0];
//do something with the annotation...
}
If the annotation wasn't selected, another simple alternative is to use an ivar to hold a reference to the annotation that needs to be deleted.
Another option as MSK commented is to use objc_setAssociatedObject.
Regardless, using the superview assuming the view hierarchy is in a certain way is not a good idea.
来源:https://stackoverflow.com/questions/11783880/access-an-alertviews-calling-view