我有以下简单的代码:
self.departureAnnotation = [[UserAnnotation alloc] init];
self.departureAnnotation.coordinate = self.map.centerCoordinate;
[self.map addAnnotation:self.departureAnnotation];
[self.map selectAnnotation:self.departureAnnotation animated:YES];
这段代码应该做的(显然)是将注释添加到 map 并立即选择它。
尽管如此,在运行 iOS 5.1.1 的未越狱 iPhone 4S 上,这段代码并未选择注释(标注未显示),但这在 iOS 6 模拟器中完美运行。
为了解决这个问题,我做了以下操作,这基本上将 pin 的选择延迟了 0.2 秒,这是我不喜欢的:
self.departureAnnotation = [[UserAnnotation alloc] init];
self.departureAnnotation.coordinate = self.map.centerCoordinate;
[self.map addAnnotation:self.departureAnnotation];
[NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(selectPin:) userInfo:self.departureAnnotation repeats:NO];
- (void)selectPin:(NSTimer *)timer
{
[self.map selectAnnotation:timer.userInfo animated:YES];
}
为什么会发生这种情况?
PS:另外,按照相同的模式,如果我检查 [self.map viewForAnnotation: self.departureAnnotation]
而不是选择 pin,则 View 为零。经过那 0.2 秒的延迟后,就OK了。
最佳答案
MKMapView
可能需要运行循环周期才能完成,然后才能为您提供注释 View /选择注释。如果是这样,请不要使用计时器,将您的 selectAnnotation:animated:
分派(dispatch)到下一个运行循环周期...
dispatch_async( dispatch_get_main_queue(), ^{
[self.map selectAnnotation:self.departureAnnotation animated:YES];
} );
...可能会有所帮助。
文档还指出您需要立即添加注释,因为 MKMapView
决定哪个注释在屏幕上/不在屏幕上,因此它会返回或不返回 View 。
只需我的 0.02 美元...
关于objective-c - MKMapView addAnnotation 未立即添加注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13530102/