可以帮我制作带有附加参数Color的自定义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
}
我的解决方案不起作用,我无法弄明白为什么。折线完全不可见。我是SWIFT的初学者,所以我认为问题在于我的CustomPolyline
课程。
谢谢你的帮助。
答案 0 :(得分:11)
它可以比我更简单:
<强>类强>
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;
}
答案 1 :(得分:2)
正如用户3470987指出的那样,修改默认的'rendererForOverlay&#39;可能会出现问题。委托功能。如果您想添加除MKPolyline以外的其他类型的叠加层,也可能会很困难。
类
import Foundation
import MapKit
class Polyline: MKPolyline {
var color: UIColor?
}
渲染功能
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)
}
答案 2 :(得分:0)
另一种最简单的解决方案:
extension UIColor {
static var rendererColor: UIColor {
return UIColor(red: 65/255, green: 65/255, blue: 65/255, alpha: 1)
}
}
以及用途:
renderer.strokeColor = UIColor.renderer