iPhone MKMapView标注观察者一次可选择。

3
我在MKMapView上有不同的自定义地图标注,创建自定义视图时我会添加一个观察者并禁用默认弹出窗口。
在MapViewController.m文件的顶部:
static NSString* const ANNOTATION_SELECTED_DESELECTED = @"annotationSelectedOrDeselected";

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation {
    // Things here.

    // Enable the view.
    [annotationView setEnabled:YES];

    // Delete the default popup.
    [annotationView setCanShowCallout:NO];

    // Add an observer on the annotation.
    [annotationView addObserver:self
                     forKeyPath:@"selected"
                        options:NSKeyValueObservingOptionNew
                        context:ANNOTATION_SELECTED_DESELECTED];

    return annotationView;
}

然后在观察函数中,我创建弹出框并显示:

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    NSString *action = (NSString *)context;

    if ([action isEqualToString:ANNOTATION_SELECTED_DESELECTED]) {
        BOOL annotationSelected = [[change valueForKey:@"new"] boolValue];

        if (annotationSelected) {
            // Actions when annotation selected.
            // I create the appropriate popover here and display it in self.view
        }
    } else {
        // Actions when annotation deselected.
        NSLog(@"Annotation deselected! But never pass here...");
    }
}

我的问题是当我的弹出框被关闭后,如果我想选择同一个注释,它就无法工作...就好像观察者的状态仍然是“激活”的一样。因此,为了选择我的注释,我需要先选择另一个注释,然后才能再次选择它...不能连续两次选择相同的注释很烦人。
请帮帮我!谢谢。

你的代码格式有问题 - 请重新格式化以使其更易读。 - Echelon
我已经重新格式化了代码,抱歉。 - Dachmt
3个回答

2

我使用了[mapview deselectAnnotation:annotation animated:FALSE];,目前看来它起作用了。


1

尝试更改:

BOOL annotationSelected = [[change valueForKey:@"new"] boolValue];

BOOL annotationSelected = [[change valueForKey:NSKeyValueObservingOptionNew] boolValue];

我记得自己也遇到过这个问题。


您的解决方案出现了一个警告。我的做法是在注释被选中后取消选择注释:[mapView deselectAnnotation:incidentAnnotation animated:NO]; - Dachmt

1

将传递给observeValueForKeyPath函数的对象名称保存为临时对象,例如oldObject

然后在您关闭popOverView的函数中编写以下代码。

[mapView deselectAnnotation:[oldObject annotation] animated:NO];


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接