swiftmkpolyline

Change Polyline Color Swift Xcode


I'm attempting to conditionally change the color of a polyline, but need to check a variable that lies outside the renderer method. As far as I know I can't pass an additional variable to the renderer method. Suggestions?

MKPolyline is initialized in viewDidLoad() along with variable x below is renderer function

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)
}

if x != y, then I want renderer.strokeColor = UIColor.green


Solution

  • If x and y are properties of your View Controller, you can reference them just like any variable in the renderer method:

    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)
    }
    

    If x and y are specific to each overlay, you need to subclass 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
        }
    }