您可以创建自己的注释视图类,该类观察您将mapType
在地图视图的属性更改时发布的自定义通知:
@interface MyAnnotationView : MKAnnotationView
@property (nonatomic, strong) id<NSObject> observer;
@end
static NSString *kMapTypeChangeNotificationKey = @"com.domain.app.maptypechange";
@implementation MyAnnotationView
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self.observer];
}
- (instancetype)initWithAnnotation:(id<MKAnnotation>)annotation reuseIdentifier:(NSString *)reuseIdentifier mapType:(MKMapType)mapType {
self = [super initWithAnnotation:annotation reuseIdentifier:reuseIdentifier];
if (self) {
[self updateImageBasedUponMapType:mapType];
typeof(self) __weak weakSelf = self;
self.observer = [[NSNotificationCenter defaultCenter] addObserverForName:kMapTypeChangeNotificationKey object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) {
MKMapType mapType = [note.userInfo[@"mapType"] unsignedIntegerValue];
[weakSelf updateImageBasedUponMapType:mapType];
}];
}
return self;
}
- (void)updateImageBasedUponMapType:(MKMapType)mapType {
if (mapType == MKMapTypeStandard) {
self.image = [UIImage imageNamed:@"whitePin.png"];
} else if (mapType == MKMapTypeSatellite) {
self.image = [UIImage imageNamed:@"greyPin.png"];
} else {
NSLog(@"Unexpected mapType %lu", (unsigned long)mapType);
}
}
@end
显然,这意味着当您实例化它时,您必须将其传递给映射类型的引用:
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation {
if ([annotation isKindOfClass:[MKUserLocation class]]) { return nil; }
static NSString *reuseIdentifier = @"MyCustomAnnotation";
MyAnnotationView *annotationView = (id)[mapView dequeueReusableAnnotationViewWithIdentifier:reuseIdentifier];
if (annotationView) {
annotationView.annotation = annotation;
} else {
annotationView = [[MyAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:reuseIdentifier mapType:mapView.mapType];
annotationView.canShowCallout = true;
}
return annotationView;
}
现在,当您更新mapType
地图时,还要发布此自定义注释:
- (IBAction)changedValueSegmentControl:(UISegmentedControl *)sender {
if (sender.selectedSegmentIndex == 0) {
self.mapView.mapType = MKMapTypeStandard;
} else if (sender.selectedSegmentIndex == 1) {
self.mapView.mapType = MKMapTypeSatellite;
}
[[NSNotificationCenter defaultCenter] postNotificationName:kMapTypeChangeNotificationKey object:self userInfo:@{@"mapType" : @(self.mapView.mapType)}];
}