MKMapViewDelegate:如何在 rendererForOverlay 中识别覆盖

MKMapViewDelegate: How to identifiy overlay in rendererForOverlay

我正在向 MKMapView 添加两个不同的 MKGeodesicPolyline 实例,就像这样

CLLocation *LAX = [[CLLocation alloc] ...];
CLLocation *JFK = [[CLLocation alloc] ...];
CLLocation *LHR = [[CLLocation alloc] ...];

CLLocationCoordinate2D laxToJfkCoords[2] = {LAX.coordinate, JFK.coordinate};
CLLocationCoordinate2D jfkToLhrCoords[2] = {JFK.coordinate, LHR.coordinate};

MKGeodesicPolyline *laxToJfk = [MKGeodesicPolyline polylineWithCoordinates:laxToJfkCoords count:2];
MKGeodesicPolyline *jfkToLhr = [MKGeodesicPolyline polylineWithCoordinates:jfkToLhrCoords count:2];

[mapView addOverlay:laxToJfk];
[mapView addOverlay:jfkToLhr];

我想用不同的样式渲染这两个叠加层,需要在 rendererForOverlay 委托方法中进行配置。

- (MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id <MKOverlay>)overlay {
    if (![overlay isKindOfClass:[MKPolyline class]]) {
        return nil;
    }

    MKPolylineRenderer *renderer = [[MKPolylineRenderer alloc] initWithPolyline:(MKPolyline *)overlay];
    renderer.lineWidth = 3.0f;

    // How to set different colors for LAX-JFK and JFK-LHR?
    renderer.strokeColor = [UIColor blueColor];

    return renderer;
}

我的问题是在上述方法中有哪些选项可以识别两种不同的叠加层?

这是我目前的考虑:

  1. 子类化:不是一个选项,因为 MKGeodesicPolyline 是通过静态工厂方法初始化的。
  2. 在属性中保留对叠加层的引用,然后将委托的 overlay 参数与那些进行比较。这确实有效,但感觉有点笨拙。此外,对于两个以上的覆盖,需要使用 NSSetNSArray.
  3. 来扩展此方法

还有什么我可以做的来简化这个吗? MKGeodesicPolyline 似乎没有任何可用于标记的属性。

子类化的一种替代方法是使用 associated objects。但通常不鼓励使用它。

一个更长但更稳定的解决方案是制作自定义 MKOverlayMKOverlayRenderer,将它们的大部分实现转发到 MKGeodesicPolyline 和 [=13 的私有实例=] 分别。然后你可以添加自定义属性来设置颜色。