How to make custom MKPolyline in SWIFT with additional argument - color

后端 未结 3 1007
臣服心动
臣服心动 2021-01-12 10:53

Can any help me with making custom MKPolyline with additional argument Color?

CustomPolyline.swift

import Foundation
im         


        
相关标签:
3条回答
  • 2021-01-12 11:21

    It can be done much more simpler than I throught:

    Class

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

    Init

    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;
    
        }
    
    0 讨论(0)
  • 2021-01-12 11:37

    Another solution most easy:

    extension UIColor {
        static var rendererColor: UIColor {
            return UIColor(red: 65/255, green: 65/255, blue: 65/255, alpha: 1)
        }
    }
    

    And the use:

    renderer.strokeColor = UIColor.renderer
    
    0 讨论(0)
  • 2021-01-12 11:42

    As user3470987 pointed out, there might be an issue in modifying the default 'rendererForOverlay' delegate function. It could also prove difficult if you'd like to add overlays of other types than MKPolyline.

    Class

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

    Render 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)
    
    }
    
    0 讨论(0)
提交回复
热议问题