使用以下教程中的代码http://www.zenbrains.com/blog/en/2010/05/detectar-cuando-se-selecciona-una-anotacion-mkannotation-en-mapa-mkmapview/,我能够为每个 MKAnnotation 添加观察者并接收选择/取消选择状态的通知。
我试图在选择注释之上添加一个 UIView 以显示有关该位置的相关信息。此信息不能在图钉标注允许的 2 行(标题/副标题)中传达。
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context {
Annotation *a = (Annotation *)object;
// Alternatively attempted using:
//Annotation *a = (Annotation *)[mapView.selectedAnnotations objectAtIndex:0];
NSString *action = (NSString *)context;
if ([action isEqualToString:ANNOTATION_SELECTED_DESELECTED]) {
BOOL annotationSelected = [[change valueForKey:@"new"] boolValue];
if (annotationSelected) {
// Actions when annotation selected
CGPoint origin = a.frame.origin;
NSLog(@"origin (%f, %f) ", origin.x, origin.y);
// Test
UIView *v = [[UIView alloc] init];
[v setBackgroundColor:[UIColor orangeColor]];
[v setFrame:CGRectMake(origin.x, origin.y , 300, 300)];
[self.view addSubview:v];
[v release];
}else {
// Accions when annotation deselected
}
}
}
结果使用Annotation *a = (Annotation *)object
origin (154373.000000, 197135.000000)
origin (154394.000000, 197152.000000)
origin (154445.000000, 197011.000000)
结果使用Annotation *a = (Annotation *)[mapView.selectedAnnotations objectAtIndex:0];
origin (0.000000, 0.000000)
origin (0.000000, 0.000000)
origin (0.000000, 0.000000)
数字很大。它们与视图 (1024 x 768) 无关。我相信它们是相对于整个地图的。我如何能够检测到相对于整个视图的确切坐标,以便我可以适当地定位我的视图?
笔记:
刚刚发现这两种方法可能可以在更简单的实现中完成与上面的代码相同的事情。
选择注释视图
– mapView:didSelectAnnotationView:
– mapView:didDeselectAnnotationView: