OGeek|极客世界-中国程序员成长平台

标题: ios - 获取 MapView.annotations 数组中 MKAnnotation 的索引 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 18:01
标题: ios - 获取 MapView.annotations 数组中 MKAnnotation 的索引

我正在使用 MKMapView 和 MKAnnotations 在 xCode 中制作应用程序。如果您添加了两个以上的注释,则额外的航点颜色(PinAnnotations)应更改为紫色。

因此我需要注释中的标记、IndexPath 或 ID 之类的东西来识别 MKAnnotation 函数中的 MKAnnotation。我用了这行代码:

    - (MKAnnotationView *)mapViewMKMapView *)mapView viewForAnnotationid<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!

最好的问候和感谢!



Best Answer-推荐答案


推荐的处理方法是创建自己的类,该类实现 MKAnnotation 协议(protocol),并具有一个属性,您可以在 viewForAnnotations 期间检查该属性以查看要使用的颜色。 MKMapView 中的 annotations 数组不能保证按照您向 map 添加注释的顺序。您可以添加 annoy,annoy 然后 annoy,但您可能会返回 [anno2, anno3, anno1]。这就是它的方式,你无法改变它。因此,您可以保留自己的注释数组,这些注释不会被重新排列。或者如果合适的话,可以使用额外属性的想法。

你不应该做的一件事是在 viewForAnnotation 函数期间添加更多注释,这真的很糟糕。

关于ios - 获取 MapView.annotations 数组中 MKAnnotation 的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21098974/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4