更改折线颜色 Swift Xcode

Change Polyline Color Swift Xcode

我正在尝试有条件地更改折线的颜色,但需要检查位于渲染器方法之外的变量。据我所知,我无法将附加变量传递给渲染器方法。建议?

MKPolyline 在 viewDidLoad() 中与变量 x 一起初始化 下面是渲染器函数

extension ViewController {
  func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> 
  MKOverlayRenderer {
    if overlay is MKPolyline {

        let renderer = MKPolylineRenderer(overlay: overlay)
        renderer.strokeColor = UIColor.blue
        renderer.lineWidth = 3
        return renderer
    }
    return MKOverlayRenderer(overlay: overlay)
}

如果 x != y,那么我想要 renderer.strokeColor = UIColor.green

如果 xy 是视图控制器的属性,您可以像在渲染器方法中引用任何变量一样引用它们:

extension ViewController {
  func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
    if overlay is MKPolyline {          
        let renderer = MKPolylineRenderer(overlay: overlay)
        renderer.strokeColor = x == y ? UIColor.blue : UIColor.green
        renderer.lineWidth = 3
        return renderer
    }
    return MKOverlayRenderer(overlay: overlay)
}

如果xy特定于每个叠加层,则需要子类化MKPolyline:

class MyPolyline: MKPolyline {
    // Initialize them specific to your needds
    var x = 0
    var y = 0
}

extension ViewController {
    func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
        guard let overlay = overlay as? MyPolyline else {
            return MKOverlayRenderer(overlay: overlay)
        }

        let renderer = MKPolylineRenderer(overlay: overlay)
        // You can also add a strokeColor as a computed property to the MyPolyline class
        renderer.strokeColor = overlay.x == overlay.y ? UIColor.blue : UIColor.green
        renderer.lineWidth = 3
        return renderer
    }
}