我正在 xCode 中使用 MKMapView 和 MKAnnotations 制作一个应用程序。如果您进行两个以上注释,则额外的航点颜色 (PinAnnotations) 应更改为紫色。
因此我需要注释中的标签、IndexPath 或 ID 来标识 MKAnnotation 函数中的 MKAnnotation。我使用了这行代码:
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
MKPinAnnotationView *pinView = nil;
if (annotation != mkMap.userLocation)
{
static NSString *defaultPinID = @"aPin";
pinView = (MKPinAnnotationView *)[mkMap dequeueReusableAnnotationViewWithIdentifier:defaultPinID];
if (pinView == nil)
{
pinView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:defaultPinID];
pinView.canShowCallout = YES;
pinView.tag = mapView.annotations.count; // tag is not available for annotation in this function
}
}
pinView.canShowCallout = YES;
pinView.animatesDrop = YES;
pinView.draggable = YES;
if ([annotation isKindOfClass:[MKUserLocation class]])
return pinView;
NSLog(@"Annotation-Index: %d", [mapView.annotations indexOfObject:annotation]);
NSLog(@"MapView.annotations.count = %d", mapView.annotations.count);
if (1 == [mapView.annotations indexOfObject:annotation])
pinView.pinColor = MKPinAnnotationColorGreen;
else if (1 < [mapView.annotations indexOfObject:annotation])
{
pinView.pinColor = MKPinAnnotationColorRed;
// checkes for extra waypoints
if (2 < mapView.annotations.count)
{
for (int i = 2; i > mapView.annotations.count; i++)
{
MKPinAnnotationView *aView = [mapView.annotations objectAtIndex:i];
aView.pinColor = MKPinAnnotationColorPurple;
[mapView removeAnnotation:mapView.annotations[i]];
NSMutableArray *a = [[NSMutableArray alloc] init];
[a replaceObjectAtIndex:i withObject:aView];
[mapView addAnnotations:a];
}
}
}
return pinView;
}
我已经用谷歌搜索了这个问题,并找到了很多像我一样的解决方案
int AnnotationIndex = [mapView.annotations indexOfObject:annotation];
但是这个函数的输出(Annotation-Index)引起了我的注意。有时一切都很好,但是 Annotation-Index 具有正确的值,但大多数时候这些值似乎是随机生成的,并且如果 MapView.annotations.count 只是 3,则比例也会从 0 到 10!
致以诚挚的问候和感谢!
最佳答案
处理此问题的推荐方法是创建您自己的类,该类实现 MKAnnotation 协议(protocol),并具有一个属性,您可以在 viewForAnnotations
期间检查该属性以查看要使用的颜色。 MKMapView 中的 annotations
数组不保证按照您向 map 添加注释的顺序排列。你可以添加 annoy、annoy、然后 annoy,但你可能会返回 [anno2、anno3、anno1]。事情就是这样,你无法改变。因此,您可以保留自己的注释数组,而不会重新排列。或者如果合适的话可以使用额外的属性(property)想法。
您不应该做的一件事是在 viewForAnnotation
函数中添加更多注释,这真的很困惑。
关于ios - 获取 MapView.annotations 数组中 MKAnnotation 的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21098974/