MKMapViewDelegate:如何识别rendererForOverlay中的叠加层 [英] MKMapViewDelegate: How to identifiy overlay in rendererForOverlay
问题描述
我要将两个不同的 MKGeodesicPolyline
实例添加到 MKMapView
这样
I'm adding two different MKGeodesicPolyline
instances to an MKMapView
like this
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
委托方法中进行配置.
I want to render both of these overlays with different styles which need to be configured in the rendererForOverlay
delegate method.
- (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;
}
我的问题是,在上述方法中,有哪些选项可以识别两个不同的叠加层?
My question is what options are there to identify the two different overlays in the above method?
这是我到目前为止所考虑的:
Here's what I considered so far:
- 子类化:这不是一个选择,因为
MKGeodesicPolyline
是通过静态工厂方法初始化的. - 在属性中保留对叠加层的引用,然后将委托的
overlay
参数与这些参数进行比较.这确实有效,但感觉有点笨拙.此外,对于两个以上的叠加层,需要使用NSSet
或NSArray
来扩展此方法.
- Subclassing: Not an option because
MKGeodesicPolyline
is initialized through a static factory method. - Keep references to the overlays in properties and then compare the delegate's
overlay
parameter against those. This does work but it feels a little clumsy. Also, for more than two overlays this approach would need to be extended by using anNSSet
or anNSArray
.
还有什么我可以做些简化的事情吗?似乎 MKGeodesicPolyline
没有任何可用于标记的属性.
Is there anything else I could do to simplify this? It seems that MKGeodesicPolyline
does not possess any properties that could be used for tagging.
推荐答案
子类化的一种替代方法是使用关联对象.但是通常不鼓励使用它.
One alternative to subclassing is to use associated objects. But its use is often discouraged.
一个更长久但更稳定的解决方案是制作一个自定义 MKOverlay
和一个 MKOverlayRenderer
,将其大多数实现转发到 MKGeodesicPolyline
和 MKPolylineRenderer
.然后,您可以添加一个自定义属性来设置颜色.
A longer, but more stable solution, is to make a custom MKOverlay
and a MKOverlayRenderer
that forward most of their implementations to a private instance of MKGeodesicPolyline
and MKPolylineRenderer
respectively. Then you can add a custom property to set the color.
这篇关于MKMapViewDelegate:如何识别rendererForOverlay中的叠加层的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!