【问题标题】:how to auto select annotation when add to mapkit添加到mapkit时如何自动选择注释
【发布时间】:2014-05-19 13:54:10
【问题描述】:

我有一张地图,我可以用代码在其中添加图钉(注释)。 我希望在运行我的应用程序时以及在我的应用程序中添加注释时自动选择此注释,当单击地图而不是注释我的注释时取消选择。 我可以处理选择和取消选择我的注释,但肯定必须单击注释直到选择并单击地图(另一个地方而不是注释)直到我的注释取消选择。

我不想要这个。我希望在运行我的应用程序时自动选择我的注释,并且只需要单击地图上的另一个位置,直到我的注释取消选择。

请指导我。这是我处理选择/取消选择注释的代码:

static NSString* const ANNOTATION_SELECTED_DESELECTED = @"mapAnnotationSelectedOrDeselected";


- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    NSLog(@"2");
    NSString *action = (__bridge NSString *)context;
    if ([action isEqualToString:ANNOTATION_SELECTED_DESELECTED]) {
        BOOL annotationSelected = [[change valueForKey:@"new"] boolValue];
        if (annotationSelected) {
            NSLog(@"Annotation was selected, do whatever required");
        }else {
            NSLog(@"Annotation was deselected, do what you must");

        }
    }
}
- (void)mapView:(MKMapView *)mapView didAddAnnotationViews:(NSArray *)views {
    if ([mapViews.annotations count] > 1) {
        for (MKAnnotationView *anAnnotationView in views) {
            [anAnnotationView addObserver:self forKeyPath:@"selected" options:NSKeyValueObservingOptionNew context:(__bridge void *)(ANNOTATION_SELECTED_DESELECTED)];
        }
    }

}
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation {
    MKPinAnnotationView *pinView = (MKPinAnnotationView*)[self.mapView dequeueReusableAnnotationViewWithIdentifier:@"Prospects"];
    if ([annotation isKindOfClass:[MKUserLocation class]]){
        return nil;  //return nil to use default blue dot view
    }
    else if(pinView == nil) {

        pinView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"Prospects"];
        pinView.pinColor = MKPinAnnotationColorPurple;
        pinView.animatesDrop = YES;
        pinView.draggable = NO;
    }
    return pinView;
}

【问题讨论】:

    标签: ios objective-c annotations mapkit mkannotation


    【解决方案1】:

    选择指定的注解并为其显示标注视图。

    [mapView selectAnnotation:pinView animated:YES]; //这里 pinView 是你的注解,mapview 是你的地图

    如果指定的注释不在屏幕上,因此没有关联的注释视图,则此方法无效。

    点击地图上的另一个地方,直到我的注释被取消。 它是 mapview 的默认行为。

    MKMapView Reference

    opening-callout-of-annotation-on-map-automatically-when-map-first-load

    【讨论】:

    • 我收到此错误:错误:尝试选择尚未添加的注释
    • 你需要在向地图添加注解后,在 [mapView addAnnotation:pinView]; 之后执行此操作
    【解决方案2】:

    与 swift 3 相同的解决方案

     func mapView(_ mapView: MKMapView, didAdd views: [MKAnnotationView]) {
        self.mapView.selectAnnotation(self.mapView.annotations[0], animated: true)
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多