如何使用附加参数 – 颜色在SWIFT中自定义MKPolyline

任何可以帮助我与自定义MKPolyline额外的参数颜色?

CustomPolyline.swift

 import Foundation import MapKit class CustomPolyline : MKPolyline { let coordinates: UnsafeMutablePointer<CLLocationCoordinate2D> let count : Int = 0 let color : String = "ff0000" init(coordinates: UnsafeMutablePointer<CLLocationCoordinate2D>, count: Int, color: String) { self.coordinates = coordinates self.count = count self.color = color } } 

在里面

 Polyline = CustomPolyline(coordinates: &Path, count: Path.count, color: "ff0000") self.mapView.addOverlay(Polyline) func mapView(mapView: MKMapView!, rendererForOverlay overlay: MKOverlay!) -> MKOverlayRenderer! { if (overlay is CustomPolyline) { var pr = MKPolylineRenderer(overlay: overlay); pr.strokeColor = UIColor.colorWithRGBHex(0xff0000).colorWithAlphaComponent(0.5); pr.lineWidth = 10; return pr; } return nil } 

我的解决scheme不起作用,我不明白为什么。 折线不可见。 我是SWIFT的初学者,所以我认为这个问题与我的CustomPolyline类有关。 感谢帮助。

它可以做得比我更简单:

 import Foundation import MapKit class CustomPolyline : MKPolyline { var color: String? } 

在里面

 cPolyline = CustomPolyline(coordinates: &Path, count: Path.count) cPolyline.color = "#ff0000" self.mapView.addOverlay(cPolyline) func mapView(mapView: MKMapView!, rendererForOverlay overlay: CustomPolyline!) -> MKOverlayRenderer! { var pr = MKPolylineRenderer(overlay: overlay); pr.strokeColor = UIColor(rgba: overlay.color); pr.lineWidth = 10; return pr; } 

正如user3470987指出的那样,修改默认的“rendererForOverlay”委托函数可能会有问题。 如果您想要添加除MKPolyline以外的其他types的叠加层,也可能会遇到困难。

 import Foundation import MapKit class Polyline: MKPolyline { var color: UIColor? } 

渲染function

 func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer { if let polyline = overlay as? Polyline { let polylineRenderer = MKPolylineRenderer(overlay: polyline) polylineRenderer.strokeColor = polyline.color polylineRenderer.lineWidth = 3 return polylineRenderer } return MKOverlayRenderer(overlay: overlay) }