2016-01-03 2 views
1

Я не могу найти точный вопрос.iOS MapKit - Можно ли изменить вывод карты на основе типа карты?

У меня есть некоторые пользовательские контакты, которые выглядят нормально на стандартной карте. Я хочу использовать другие контакты, если карта изменится на Satellite или Hybrid.

Возможно ли это?

Я попытался это до сих пор:

annotationImageName = @"blackPin.png"; 

    if (segment == 1) { 
     NSLog(@"segment 1"); 
     annotationImageName = @"whitePin.png"; 
    } 
    else if (segment == 2) { 
     NSLog(@"segment 2"); 
     annotationImageName = @"greyPin.png"; 
    } 


} 

......

MKAnnotationView *annotationView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"annotationPin"]; 

annotationView.image = [UIImage imageNamed:annotationImageName]; 

ответ

1

Вы можете сделать свой собственный класс просмотра аннотаций, который наблюдает пользовательское уведомление, что вам будет опубликован при изменении свойства 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)}]; 
} 
+0

Спасибо, сэр. Какой блестящий ответ. –

+0

@DavidDelMonte - В моем первоначальном ответе использовался KVO, но это могло бы представлять проблемы, когда отображение карты было освобождено. Это немного менее изящно, но вы можете использовать пользовательские уведомления, как показано в моем пересмотренном ответе. – Rob

+0

Почти у него есть. Возможно, ошибка выше? Я получаю ошибку компиляции в 'annotationView = [[MyAnnotationView alloc] initWithAnnotation: annotation reuseIdentifier: reuseIdentifier mapType: mapView.mapType]' –

1
- (void) changeMapType: (id)sender 
{ 
    annotationImageName = @"blackPin.png"; 

     if (mapView.mapType == MKMapTypeStandard) 

     { 

      mapView.mapType = MKMapTypeSatellite; 
      NSLog(@"segment 1"); 
      annotationImageName = @"whitePin.png"; 
     } 
     else 
      { 
      mapView.mapType = MKMapTypeStandard; 
      NSLog(@"segment 2"); 
      annotationImageName = @"greyPin.png"; 
      } 

    } 

MKAnnotationView *annotationView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"annotationPin"]; 

annotationView.image = [UIImage imageNamed:annotationImageName]; 
+0

Спасибо за то, что Акаш, и добро пожаловать в СО. Я не думаю, что annotationView переименовывается, когда сегмент типа карты изменяется. –